How to strip part of an NSString after the first instance of a character? - ios

I would like to strip part of an NSString.
in the following string I would like to just grab the digits before the "/sampletext1/sampletext2/sampletext3"
1464/sampletext1/sampletext2/sampletext3
I have already stripped out the web address before the digits, but can't figure out the rest. Sometimes the digits could be 3 or 4 or 5 digits long.
thanks

Get the index of the first / character then get the substring up to that location.
NSString *stuff = #"1464/sampletext1/sampletext2/sampletext3";
NSString *digits;
NSRange slashRange = [stuff rangeOfString:#"/"];
if (slashRange.location != NSNotFound) {
digits = [stuff substringToIndex:slashRange.location];
} else {
digits = stuff;
}

You mentioned that you extracted a web address from the front, so I'm guessing you're dealing with either something like http://localhost:12345/a/b/c or http://localhost/12345/a/b/c.
In either case, you can convert your string to an NSURL and take advantage of its built-in features:
// Port
NSURL *URL = [NSURL URLWithString:#"http://localhost:12345/a/b/c"];
NSUInteger port = URL.port.integerValue;
// Path component
NSURL *URL = [NSURL URLWithString:#"http://localhost/12345/a/b/c"];
NSString *number = URL.pathComponents[1];

Use regular expressions:
NSError *error;
NSString *test = #"1464/sampletext1/sampletext2/sampletext3";
NSRegularExpression *aRegex = [NSRegularExpression regularExpressionWithPattern:#"^\\d+"
options:NSRegularExpressionCaseInsensitive
error:&error];
NSRange aRangeOfFirstMatch = [aRegex rangeOfFirstMatchInString:test options:0 range:NSMakeRange(0, [test length])];
if (aRangeOfFirstMatch.location != NSNotFound) {
NSString *matchedString = [test substringWithRange:aRangeOfFirstMatch];
NSLog(#"matchedString = %#", matchedString);
}

Related

Regex for a string combination

NSString *fmtpAudio = #"a=fmtp:111 ";
NSString *stereoString = #";stereo=1;sprop-stereo=1";
NSArray *componentArray = [localSdpMutableStr componentsSeparatedByString:fmtpAudio];
if (componentArray.count >= 2) {
NSString *component = [componentArray objectAtIndex: 1];
NSArray *fmtpArray = [component componentsSeparatedByString:#"\r\n"];
if (fmtpArray.count > 1) {
NSString *fmtp = [fmtpArray firstObject];
NSString *fmtpAudioOld = [NSString stringWithFormat:#"%#%#", fmtpAudio, fmtp];
fmtpAudio = [NSString stringWithFormat:#"%#%#%#", fmtpAudio, fmtp, stereoString];
NSString *stereoEnabledSDP = [NSString stringWithString: localSdpMutableStr];
stereoEnabledSDP = [stereoEnabledSDP stringByReplacingOccurrencesOfString: fmtpAudioOld withString: fmtpAudio];
localSdpMutableStr.string = stereoEnabledSDP;
}
}
Consider below example String:
a=fmtp:93 av=2\r\n
a=fmtp:111 av=1\r\n
a=fmtp:92 av=2\r\n
In the above example string, a=fmtp:111 can appear anywhere in the string.
We have to get the string between a=fmtp:111 and the next first appearance of \r\n which is av=1 in our case
Now we have to append ;stereo=1;sprop-stereo=1 to av=1 and append back to the original string.
The final output should be
a=fmtp:93 av=2\r\n
a=fmtp:111 av=1;stereo=1;sprop-stereo=1\r\n
a=fmtp:92 av=2\r\n
Is it possible to achieve the above chunk of logic with Replace with Regex pattern?
You can use
NSError *error = nil;
NSString *fmtpAudio = #"^a=fmtp:111 .*";
NSString *stereoString = #"$0;stereo=1;sprop-stereo=1";
NSString *myText = #"a=fmtp:93 av=2\r\na=fmtp:111 av=1\r\na=fmtp:92 av=2";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:fmtpAudio options:NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate: stereoString];
NSLog(#"%#", modifiedString);
Output:
a=fmtp:93 av=2
a=fmtp:111 av=1;stereo=1;sprop-stereo=1
a=fmtp:92 av=2
See the regex demo.
Details
^ - start of a line (^ starts matching line start positions due to the options:NSRegularExpressionAnchorsMatchLines option)
a=fmtp:111 - a literal string
.* - any zero or more chars other than line break chars as many as possible.
The $0 in the replacement pattern is the backreference to the whole match value.

How to add a character at start and end of every word in NSString

Suppose i have this:
NSString *temp=#"its me";
Now suppose i want ' " ' in start and end of every word, how can i achieve it to get the result like this:
"its" "me"
Do i have to use regular expressions?
If you have punctuation inside the string, splitting with a space might not be enough.
Use the word boundary \b: it matches both the leading and trailing word boundaries (that is, it will match an empty space right between word and non-word characters and also at the start/end of the string if followed/preceded with a word character.
NSError *error = nil;
NSString *myText = #"its me";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\b" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate:#"\""];
NSLog(#"%#", modifiedString); // => "its" "me"
See the IDEONE demo
See more details on the regex syntax in Objective C here.
You can do something like,
NSString *str = #"its me";
NSMutableString *resultStr = [[NSMutableString alloc]init];
NSArray *arr = [str componentsSeparatedByString:#" "];
for (int i = 0; i < arr.count; i++) {
NSString *tempStr = [NSString stringWithFormat:#"\"%#\"",arr[i]];
resultStr = [resultStr stringByAppendingString:[NSString stringWithFormat:#"%# ",tempStr]];
}
NSLog(#"result string is : %#",resultStr);
Hope this will help :)

I want to remove static text from string - iOS

Hi I have a News Reader and I keep getting a string like this -
two New York police officers shot dead in 'ambush'
I want the string two New York police officers shot dead in ambush
How can I scan from & to ; and then delete occurrences of the scan.
I created a scanner like so -
NSString *webString222222 = filteredTitle2;
NSScanner *stringScanner222222 = [NSScanner scannerWithString:webString222222];
NSString *content222222 = [[NSString alloc] init];
[stringScanner222222 scanUpToString:#"&" intoString:Nil];
[stringScanner222222 scanUpToString:#";" intoString:&content222222];
NSString *filteredTitle222 = [content222222 stringByReplacingOccurrencesOfString:content222222 withString:#""];
NSString *filteredTitle22 = [filteredTitle222 stringByReplacingOccurrencesOfString:#"&" withString:#""];
But when I do this code the whole text disappears! Every single word.
When I check the title in my NSLog that is the only & sign in there and the only ; sign in there!
Im not sure where I went wrong here.
If the special characters you are encountering are all relatively consistent you can merely replace each of those substrings with the empty string, like so:
NSString *cleansedString = [filteredTitle2 stringByReplacingOccurrencesOfString:#"'"
withString:#""];
You can use NSRegularExpression to build proper matching pattern:
NSString *pattern = #"\\&#[0-9]+;";
NSString *str = #"two New York police officers shot dead in 'ambush'";
NSLog(#"Original test: %#",str);
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:pattern
options:NSRegularExpressionCaseInsensitive error:&error];
if (error != nil)
{
NSLog(#"ERror: %#",error);
}
else
{
NSString *replaced = [regex stringByReplacingMatchesInString:str
options:0
range:NSMakeRange(0, [str length])
withTemplate:#""];
NSLog(#"Replaced test: %#",replaced);
}
See https://developer.apple.com/library/ios/documentation/Foundation/Reference/NSRegularExpression_Class/index.html

Finding first letter in NSString and counting backwards

I'm new to IOS, and was looking for some guidance.
I have a long NSString that I'm parsing out. The beginning may have a few characters of garbage (can be any non-letter character) then 11 digits or spaces, then a single letter (A-Z). I need to get the location of the letter, and get the substring that is 11 characters behind the letter to 1 character behind the letter.
Can anyone give me some guidance on how to do that?
Example: '!!2553072 C'
and I want : '53072 '
You can accomplish this with the regex pattern: (.{11})\b[A-Z]\b
The (.{11}) will grab any 11 characters and the \b[A-Z]\b will look for a single character on a word boundary, meaning it will be surrounded by spaces or at the end of the string. If characters can follow the C in your example then remove the last \b. This can be accomplished in Objective-C like so:
NSError *error;
NSString *example = #"!!2553072 C";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(.{11})\\b[A-Z]\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
if(!regex)
{
//handle error
}
NSTextCheckingResult *match = [regex firstMatchInString:example
options:0
range:NSMakeRange(0, [example length])];
if(match)
{
NSLog(#"match: %#", [example substringWithRange:[match rangeAtIndex:1]]);
}
There may be a more elegant way to do this involving regular expressions or some Objective-C wizardry, but here's a straightforward solution (personally tested).
-(NSString *)getStringContent:(NSString *)input
{
NSString *substr = nil;
NSRange singleLetter = [input rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if(singleLetter.location != NSNotFound)
{
NSInteger startIndex = singleLetter.location - 11;
NSRange substringRange = NSMakeRange(start, 11);
substr = [tester substringWithRange:substringRange];
}
return substr;
}
You can use NSCharacterSets to split up the string, then take the first remaining component (consisting of your garbage and digits) and get a substring of that. For example (not compiled, not tested):
- (NSString *)parseString:(NSString *)myString {
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
NSArray *components = [myString componentsSeparatedByCharactersInSet:letters];
assert(components.count > 0);
NSString *prefix = components[0]; // assuming relatively new Xcode
return [prefix substringFromIndex:(prefix.length - 11)];
}
//to get rid of all non-Digits in a NSString
NSString *customerphone = CustomerPhone.text;
int phonelength = [customerphone length];
NSRange customersearchRange = NSMakeRange(0, phonelength);
for (int i =0; i < phonelength;i++)
{
const unichar c = [customerphone characterAtIndex:i];
NSString* onechar = [NSString stringWithCharacters:&c length:1];
if(!isdigit(c))
{
customerphone = [customerphone stringByReplacingOccurrencesOfString:onechar withString:#"*" options:0 range:customersearchRange];
}
}
NSString *PhoneAllNumbers = [customerphone stringByReplacingOccurrencesOfString:#"*" withString:#"" options:0 range:customersearchRange];

How do I parse a NSString?

I have a string
https://gdata.youtube.com/feeds/api/videos?q=4s-PbMuNooo
I want to get string 4s-PbMuNooo. How do I parse a NSString?
Short answer :
NSString *myString = #"https://gdata.youtube.com/feeds/api/videos?q=4s-PbMuNooo";
NSArray *components = [myString componentsSeparatedByString:#"="];
NSString *query = [components lastObject];
Problems :
1) What if the bit after the q= contains another =
2) What if the q= bit is missing?
A better answer is for you to read the documentation - there are lots of helper methods on NSString that will get you substrings. Look for rangeOfString to find out where the equals would be and subStringWithRange to get the bit you want.
EDIT: Thomas has raised a fair point about URL parsing - see his answer here
A slightly longer but more complete answer. Hope this helps:
NSURL *url = [NSURL URLWithString: #"https://gdata.youtube.com/feeds/api/videos?param1=yeah&param2="];
NSArray *listItems = [[url query] componentsSeparatedByString:#"&"];
NSMutableDictionary *keyValues = [NSMutableDictionary dictionaryWithCapacity:listItems.count];
for (NSString *item in listItems) {
NSArray *keyValue = [item componentsSeparatedByString:#"="];
NSAssert(keyValue.count == 2, #"Key value pair mismatch");
[keyValues setObject:[keyValue objectAtIndex:1] forKey:[keyValue objectAtIndex:0]];
}
NSLog(#"1: %#", [keyValues objectForKey:#"param1"]);
NSLog(#"2: %#", [keyValues objectForKey:#"param2"]);
Like this:
NSArray *listItems = [yourString componentsSeparatedByString:#"="];
NSString *myFinalString=[NSString stringWithString:[listItems objectAtIndex:1]];
I wanted to try this a bit, so here is my code that handles more than one parameters:
NSURL *url = [NSURL URLWithString:#"https://gdata.youtube.com/feeds/api/videos?p=123123&q=234"];
NSArray *queryArray = [[url query] componentsSeparatedByString:#"&"];
for (NSString *queryString in queryArray) {
NSArray *queryComponents = [queryString componentsSeparatedByString:#"="];
if ([[queryComponents objectAtIndex:0] isEqualToString:#"q"]) {
NSLog(#"Found q: %#", [queryString substringFromIndex:2]);
} else {
NSLog(#"Did not find q.");
}
}
The question and its title are badly chosen - the answers are generally right for the more general task of splitting ANY string up, but bad for splitting up URLs as this question is actually about.
Here's how to properly get the values from a URL:
To break up a URL string, first do this:
NSURL *url = [NSURL URLWithString:urlString];
Then retrieve the parameters (the part past the "?") like this:
NSString *query = [url query];
Now you can go ahead and split that query string up using componentsSeparatedByString:#"&" as shown in the other answers.

Resources