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
The substr() method extracts a part of a string. The substr() method begins at a specified position, and returns a specified number of characters. The substr() method does not change the original string. To extract characters from the end of the string, use a negative start position.
You can also split a string by a substring, using NString's componentsSeparatedByString method. You should be able to use NSString's "componentsSeparatedByCharactersInSet:" to split on multiple characters.
NSString *firstLetter = [codeString substringToIndex:1];
Substring Method (int startIndex, int length) This method is used to extract a substring that begins from specified position describe by parameter startIndex and has a specified length. If startIndex is equal to the length of string and parameter length is zero, then it will return nothing substring.
[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
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:
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.substring
to the substrings
array.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With