How to get values after "\n" character? - objective-c

I want to take all values after a new line character \n from my string. How can I get those values?

Try this:
NSString *substring = nil;
NSRange newlineRange = [yourString rangeOfString:#"\n"];
if(newlineRange.location != NSNotFound) {
substring = [yourString substringFromIndex:newlineRange.location];
}

Take a look at method componentsSeparatedByString here.
A quick example taken from reference:
NSString *list = #"Norman, Stanley, Fletcher";
NSArray *listItems = [list componentsSeparatedByString:#", "];
this will produce a NSArray with strings separated: { #"Norman", #"Stanley", #"Fletcher" }

Here is similar function which splits the string by delimeter and return array with two trimmed values.
NSArray* splitStrByDelimAndTrim(NSString *string, NSString *delim)
{
NSRange range = [string rangeOfString: delim];
NSString *first;
NSString *second;
if(range.location == NSNotFound)
{
first = #"";
second = string;
}
else
{
first = [string substringToIndex: range.location];
first = [first stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
second = [string substringFromIndex: range.location + 1];
second = [second stringByTrimmingCharactersInSet: [NSCharacterSet whitespaceCharacterSet]];
}
return [NSArray arrayWithObjects: first, second, nil];
}

Related

How to get phone number from string?

I want to extract the phone number from a NSString.
For ex: In the string Nandu # +91-(123)-456-7890, I want to extract +91-(123)-456-7890.
I have tried code like,
NSString *myString = #"Nandu # +91-(123)-456-7890";
NSString *myRegex = #"\\d{2}+\\d{3}-\\d{3}-\\d{4}";
NSRange range = [myString rangeOfString:myRegex options:NSRegularExpressionSearch];
NSString *phoneNumber = nil;
if (range.location != NSNotFound) {
phoneNumber = [myString substringWithRange:range];
NSLog(#"%#", phoneNumber);
} else {
NSLog(#"No phone number found");
}
how can I get phone number with +91 also.
You can use this Regex pattern
(\+\d{2}-\(\d{3}\)-\d{3}-\d{4})
https://regexr.com/3qcsi
Using NSCharacterSet you can get your output. see below code and let me know if you have any query then.
NSString *originalString = #"Nandu # +91-(123)-456-7890";
NSString *cleanedString = [[originalString componentsSeparatedByCharactersInSet:[[NSCharacterSet characterSetWithCharactersInString:#"0123456789-+()"] invertedSet]] componentsJoinedByString:#""];
NSLog(#"%#", cleanedString); //+91-(123)-456-7890
You can use componentsSeparatedByString
NSString *originalString = #"Nandu # +91-(123)-456-7890";
NSArray *arrayWithTwoStrings = [originalString componentsSeparatedByString:#"+"];
NSString *mobileNumberstring = [NSString stringWithFormat:#"+%#",[arrayWithTwoStrings objectAtIndex:1]];
NSLog (#"%#",mobileNumberstring);

How to remove the first space from the NSString?

I want to remove only first space in below string.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
Note: There is a space after IF_Distance and another space after
GET_Mi. I am unable to remove the space after IF_Distance.
Use rangeOfString: to locate the first space, then use stringByReplacingCharactersInRange:withString: to replace it with the empty string.
Remove space by using below code.
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *secondString = [str stringByReplacingOccurrencesOfString:#"IF_Distance " withString:#"IF_Distance"];
Try This:
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *firstStringContainingSpace = [[str componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] firstObject];//firstStringContainingSpace = IF_Distance
str = [str stringByReplacingCharactersInRange:[str rangeOfString:[NSString stringWithFormat:#"%# ",firstStringContainingSpace]] withString:firstStringContainingSpace];
Output:
str = #"IF_Distance(GET_Mi mi=km*1.4,STRING1,STRING2)";
You can remove first space by using following code:
First find space by using rangeOfString: and then remove by using stringByReplacingCharactersInRange:withString: method.
Like,
NSString *str = #"IF_Distance (GET_Mi mi=km*1.4,STRING1,STRING2)";
NSString *strSpace = #" ";
NSRange range = [str rangeOfString:strSpace];
NSString *strFinal;
if (NSNotFound != range.location) {
strFinal = [str stringByReplacingCharactersInRange:range withString:#""];
}
If you are looking for some more universal way - this is the variant of it:
- (NSString *)removeWhitespaces:(NSString *)string {
NSMutableArray * stringComponents = [[string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] mutableCopy];
NSString * fStringComponent = [stringComponents firstObject];
[stringComponents removeObject:fStringComponent];
return [fStringComponent stringByAppendingString:[stringComponents componentsJoinedByString:#" "]];
}

Replace each word in a string with (the first letter + number of characters between + last letter)

I'm using objective-c to parse a sentence here:
NSString *myString = #“Some words to form a string”;
Here is what I have so far:
NSMutableString *firstCharacters = [NSMutableString string];
NSMutableString *lastCharacters = [myString substringFromIndex:[myString length] - 1]
NSArray *arrayOfWords = [myString componentsSeparatedByString:[NSCharacterSet whitespaceCharacterSet]];
for (NSString *word in arrayOfWords) {
if ([word length] > 0) {
NSString *firstLetter = [word substringToIndex:1];
[firstCharacters appendString:lastCharacters];
and then I am really stumped at this point. I want to NSLog the recombined string so that it looks like this:
"S2e w3s to f2m a s3g"
Please try following code :
NSString *myString = #"Some words to form a string";
NSArray *wordsInSentence = [myString componentsSeparatedByString:#" "];
NSMutableArray *expectedResultArray = [[NSMutableArray alloc] init];
for (NSString *word in wordsInSentence) {
NSString *finalExpectedString = word;
if (word.length > 2) {
NSString *firstLetterInWord = [word substringToIndex:1];
NSString *lastLetterInWord = [word substringFromIndex:[word length] - 1];
finalExpectedString = [NSString stringWithFormat:#"%#%d%#", firstLetterInWord, (int)word.length - 2, lastLetterInWord];
}
[expectedResultArray addObject:finalExpectedString];
}
NSString *printString = [expectedResultArray componentsJoinedByString:#" "];
NSLog(#"Result : %#", printString);

Parsing in order with rangeOfString:

The issue I have is that I want to parse strings in order, so for instance, parsing "one three two", adding that to another string, and printing "one three two". I'm using rangeOfString:, but when I parse that string, it returns "one two three". I know that the order of parsing in my case is the placement of the if statements, but how do I parse that string in order? Here is my code:
NSString *string = #"one three two";
NSString *newString;
if ([string rangeOfString:#"one"].location != NSNotFound)
{
newString = [newString stringByAppendingString:#"one"];
}
if ([string rangeOfString:#"two"].location != NSNotFound)
{
newString = [newString stringByAppendingString:#"two"];
}
if ([string rangeOfString:#"three"].location != NSNotFound)
{
newString = [newString stringByAppendingString:#"three"];
}
NSLog(#"%#",newString);
You are doing this wrong, you should use componentsSeparatedByString: and sorting:
NSString *stringWithNumbersOrdered(NSString *input)
{
static NSArray *numberStrings = nil;
if (!numberStrings)
{
numberStrings = [NSArray arrayWithObjects:#"zero", #"one", #"two", #"three", #"four", #"five", #"six", #"seven", #"eight", #"nine", /* etc. */ nil];
}
NSArray *components = [input componentsSeparatedByString:#" "];
NSArray *componentsSorted = [components sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
int value1 = [numberStrings indexOfObject:obj1];
int value2 = [numberStrings indexOfObject:obj2];
return value1 - value2;
}];
return [componentsSorted componentsJoinedByString:#" "];
}

Objective-C: How to extract part of a String (e.g. start with '#')

I have a string as shown below,
NSString * aString = #"This is the #substring1 and #subString2 I want";
How can I select only the text starting with '#' (and ends with a space), in this case 'subString1' and 'subString2'?
Note: Question was edited for clarity
You can do this using an NSScanner to split the string up. This code will loop through a string and fill an array with substrings.
NSString * aString = #"This is the #substring1 and #subString2 I want";
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanUpToString:#"#" intoString:nil]; // Scan all characters before #
while(![scanner isAtEnd]) {
NSString *substring = nil;
[scanner scanString:#"#" intoString:nil]; // Scan the # character
if([scanner scanUpToString:#" " intoString:&substring]) {
// If the space immediately followed the #, this will be skipped
[substrings addObject:substring];
}
[scanner scanUpToString:#"#" intoString:nil]; // Scan all characters before next #
}
// do something with substrings
[substrings release];
Here is how the code works:
Scan up to a #. If it isn't found, the scanner will be at the end of the string.
If the scanner is at the end of the string, we are done.
Scan the # character so that it isn't in the output.
Scan up to a space, with the characters that are scanned stored in substring. If either the # was the last character, or was immediately followed by a space, the method will return NO. Otherwise it will return YES.
If characters were scanned (the method returned YES), add substring to the substrings array.
GOTO 1
[aString substringWithRange:NSMakeRange(13, 10)]
would give you substring1
You can calculate the range using:
NSRange startRange = [aString rangeOfString:#"#"];
NSRange endRange = [original rangeOfString:#"1"];
NSRange searchRange = NSMakeRange(startRange.location , endRange.location);
[aString substringWithRange:searchRange]
would give you substring1
Read more:
Position of a character in a NSString or NSMutableString
and
http://iosdevelopertips.com/cocoa/nsrange-and-nsstring-objects.html
Pretty simple, easy to understand version avoiding NSRange stuff:
NSArray * words = [string componentsSeparatedByCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSMutableArray * mutableWords = [NSMutableArray new];
for (NSString * word in words){
if ([word length] > 1 && [word characterAtIndex:0] == '#'){
NSString * editedWord = [word substringFromIndex:1];
[mutableWords addObject:editedWord];
}
}
Assuming that you are looking to find the first string that starts with a pound, and ends with a space, this might work. I don't have XCode in front of me, so forgive me if there's a syntax error or length off by 1 somewhere:
-(NSString *)StartsWithPound:(NSString *)str {
NSRange range = [str rangeOfString:#"#"];
if(range.length) {
NSRange rangeend = [str rangeOfString:#" " options:NSLiteralSearch range:NSMakeRange(range.location,[str length] - range.location - 1)];
if(rangeend.length) {
return [str substringWithRange:NSMakeRange(range.location,rangeend.location - range.location)];
}
else
{
return [str substringFromIndex:range.location];
}
}
else {
return #"";
}
}
Another simple solution:
NSRange hashtag = [aString rangeOfString:#"#"];
NSRange word = [[aString substringFromIndex:hashtag.location] rangeOfString:#" "];
NSString *hashtagWord = [aString substringWithRange:NSMakeRange(hashtag.location, word.location)];
This is what I'd do:
NSString *givenStringWithWhatYouNeed = #"What you want to look through";
NSArray *listOfWords = [givenStringWithWhatYouNeed componentsSeparatedByString:#" "];
for (NSString *word in listOfWords) {
if ([[word substringWithRange:NSMakeRange(0, 1)]isEqualToString:#"#"]) {
NSString *whatYouWant = [[word componentsSeparatedByString:#"#"]lastObject];
}
}
Then you can do what you need with the whatYouWant instances. If you want to know which string it is (if it's the substring 1 or 2), check the index of of word string in the listOfWords array.
I hope this helps.
A general and simple code to select all the words starting with "#" in a NSString is:
NSString * aString = #"This is the #substring1 and #subString2 ...";
NSMutableArray *selection=#[].mutableCopy;
while ([aString rangeOfString:#"#"].location != NSNotFound)
{
aString = [aString substringFromIndex:[aString rangeOfString:#"#"].location +1];
NSString *item=([aString rangeOfString:#" "].location != NSNotFound)?[aString substringToIndex:[aString rangeOfString:#" "].location]:aString;
[selection addObject:item];
}
if you still need the original string you can do a copy.
The inline conditional is used in case your selected item is the last word