How to get substring of NSString? - objective-c

If I want to get a value from the NSString #"value:hello World:value", what should I use?
The return value I want is #"hello World".

Option 1:
NSString *haystack = #"value:hello World:value";
NSString *haystackPrefix = #"value:";
NSString *haystackSuffix = #":value";
NSRange needleRange = NSMakeRange(haystackPrefix.length,
haystack.length - haystackPrefix.length - haystackSuffix.length);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(#"needle: %#", needle); // -> "hello World"
Option 2:
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"^value:(.+?):value$" options:0 error:nil];
NSTextCheckingResult *match = [regex firstMatchInString:haystack options:NSAnchoredSearch range:NSMakeRange(0, haystack.length)];
NSRange needleRange = [match rangeAtIndex: 1];
NSString *needle = [haystack substringWithRange:needleRange];
This one might be a bit over the top for your rather trivial case though.
Option 3:
NSString *needle = [haystack componentsSeparatedByString:#":"][1];
This one creates three temporary strings and an array while splitting.
All snippets assume that what's searched for is actually contained in the string.

Here's a slightly less complicated answer:
NSString *myString = #"abcdefg";
NSString *mySmallerString = [myString substringToIndex:4];
See also substringWithRange and substringFromIndex

Here's a simple function that lets you do what you are looking for:
- (NSString *)getSubstring:(NSString *)value betweenString:(NSString *)separator
{
NSRange firstInstance = [value rangeOfString:separator];
NSRange secondInstance = [[value substringFromIndex:firstInstance.location + firstInstance.length] rangeOfString:separator];
NSRange finalRange = NSMakeRange(firstInstance.location + separator.length, secondInstance.location);
return [value substringWithRange:finalRange];
}
Usage:
NSString *myName = [self getSubstring:#"This is my :name:, woo!!" betweenString:#":"];

Use this also
NSString *ChkStr = [MyString substringWithRange:NSMakeRange(5, 26)];
Note - Your NSMakeRange(start, end) should be NSMakeRange(start, end- start);

Here is a little combination of #Regexident Option 1 and #Garett answers, to get a powerful string cutter between a prefix and suffix, with MORE...ANDMORE words on it.
NSString *haystack = #"MOREvalue:hello World:valueANDMORE";
NSString *prefix = #"value:";
NSString *suffix = #":value";
NSRange prefixRange = [haystack rangeOfString:prefix];
NSRange suffixRange = [[haystack substringFromIndex:prefixRange.location+prefixRange.length] rangeOfString:suffix];
NSRange needleRange = NSMakeRange(prefixRange.location+prefix.length, suffixRange.location);
NSString *needle = [haystack substringWithRange:needleRange];
NSLog(#"needle: %#", needle);

Related

Replace specific words in NSString

what is the best way to get and replace specific words in string ?
for example I have
NSString * currentString = #"one {two}, thing {thing} good";
now I need find each {currentWord}
and apply function for it
[self replaceWord:currentWord]
then replace currentWord with result from function
-(NSString*)replaceWord:(NSString*)currentWord;
The following example shows how you can use NSRegularExpression and enumerateMatchesInString to accomplish the task. I have just used uppercaseString as function that replaces a word, but you can use your replaceWord method as well:
EDIT: The first version of my answer did not work correctly if the replaced words are
shorter or longer as the original words (thanks to Fabian Kreiser for noting that!) .
Now it should work correctly in all cases.
NSString *currentString = #"one {two}, thing {thing} good";
// Regular expression to find "word characters" enclosed by {...}:
NSRegularExpression *regex;
regex = [NSRegularExpression regularExpressionWithPattern:#"\\{(\\w+)\\}"
options:0
error:NULL];
NSMutableString *modifiedString = [currentString mutableCopy];
__block int offset = 0;
[regex enumerateMatchesInString:currentString
options:0
range:NSMakeRange(0, [currentString length])
usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
// range = location of the regex capture group "(\\w+)" in currentString:
NSRange range = [result rangeAtIndex:1];
// Adjust location for modifiedString:
range.location += offset;
// Get old word:
NSString *oldWord = [modifiedString substringWithRange:range];
// Compute new word:
// In your case, that would be
// NSString *newWord = [self replaceWord:oldWord];
NSString *newWord = [NSString stringWithFormat:#"--- %# ---", [oldWord uppercaseString] ];
// Replace new word in modifiedString:
[modifiedString replaceCharactersInRange:range withString:newWord];
// Update offset:
offset += [newWord length] - [oldWord length];
}
];
NSLog(#"%#", modifiedString);
Output:
one {--- TWO ---}, thing {--- THING ---} good

Find certain character and substring in Objective-C

I have a string..
NSString* string = #"%B999999^PDVS123456789012^PADILLA L. ^0X0000399 ?*;999999554749123456789012=00X990300000?*
What I want is to get the name PADILLA L. and 999999554749123456789012=00X990300000?*
Use NSString componentsSeparatedByString: to split the string up. First use #"^". The name will be at index 2. Then split the substring at index 3 using #";". The string at index 1 will give you the 2nd piece you want.
NSArray *substrings = [string componentsSeparatedByString:#"^"];
NSString *name = substrings[2];
name = [name stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSString *lastpart = substrings[3];
NSArray *moresubstrings = [lastpart componentsSeparatedByString:#";"];
NSString *secondPiece = moresubstrings[1];
Without more specifics here is a brute force way:
NSString* string = #"%B999999^PDVS123456789012^PADILLA L. ^0X0000399 ?*;999999554749123456789012=00X990300000?*";
NSRange nameRange = {26, 10};
NSString *name = [string substringWithRange:nameRange];
NSRange numRange = {80, 39};
NSString *num = [string substringWithRange:numRange];
The documentation is your friend: NSString Class Reference
Without knowing what the exact input pattern is (we have your n-of-1 example only), it's going to hard to say exactly how you might parse this properly; but NSRegularExpression offers what you need (in addition to other suggested approaches):
#import <Foundation/Foundation.h>
int main(int argc, char *argv[]) {
#autoreleasepool {
NSString *sampleText = #"%B999999^PDVS123456789012^PADILLA L. ^0X0000399 ?*;999999554749123456789012=00X990300000?*";
NSError *regexError = nil;
NSRegularExpressionOptions options = 0;
NSString *pattern = #"^%\\w+\\^\\w+\\^([A-Za-z\\s]+\\.).+\\?\\*\\;(.+)\\?\\*$";
NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:pattern options:options error:&regexError];
NSTextCheckingResult *match = [expression firstMatchInString:sampleText options:0 range:range];
if( match ) {
NSRange nameRange = [match rangeAtIndex:1];
NSRange numberRange = [match rangeAtIndex:2];
printf("name = %s ",[[sampleText substringWithRange:nameRange] UTF8String]);
printf("number = %s\n",[[sampleText substringWithRange:numberRange] UTF8String]);
}
}
}
This little Foundation application prints the following to the console:
name = PADILLA L. number = 999999554749123456789012=00X990300000
The regex used to analyze the input string may need to be tweaked depending on how the input string varies. Right now it is (unescaped):
^%\w+\^\w+\^([A-Za-z\s]+\.).+\?\*\;(.+)\?\*$

how to find number of images from file name?

i need to know how meny image's i have from the file name exp:
i have images call:
first file:
Splash_10001.jpg
last file:
Splash_10098.jpg
and i want to inset then to array..
for(int i = 1; i <= IMAGE_COUNT; i++)
{
UIImage* image = [UIImage imageNamed:[NSString stringWithFormat:#"%#%04d.%#",self.firstImageName,i,self.imageType]];
NSLog(#"%d",i);
[imgArray addObject:image];
}
i want to replace IMAGE_COUNT with number 98 but i need to get the numbre from the string the user send me : Splash_10098.jpg
i need to Separate the Splash_10098.jpg into: nsstring:Splash_1 int:0098 nsstring:jpg
10x all!
It depends what input are of the string is granted. In the following I would search for the dot and go backwards to the maximum of digits.
By the way I could only recommend to use the multi lingual NumberFormatter instead of relying on the default conversion.
NSString * input = #"Splash_19001.jpg";
NSRange r = [input rangeOfString:#"."];
if(r.location>4){
NSString * numberPart = [input substringWithRange: NSMakeRange(r.location-4,4)];
NSNumberFormatter *nf = [[NSNumberFormatter alloc] init];
[nf setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * number = [nf numberFromString:numberPart];
int val = [number intValue];
NSLog(#"intValue=%d",val);
}
I think this is what you're looking for
NSString *stringUserSendsYou = #"Splash_10098.jpg";
int IMAGE_COUNT = [[[stringUserSendsYou stringByReplacingOccurrencesOfString:#"Splash_1" withString:#""] stringByReplacingOccurrencesOfString:#".jpg" withString:#""] integerValue];
If the number length is fixed in the suffix, it would make sense to use a substring instead of trying to remove the prefix. Strip the extension and grab the last x characters, convert those into an int with either intValue or the NSNumberFormatter suggested by iOS, although that might be unnecessary if you are sure of the format of the string.
NSString *userProvidedString = #"Splash_10001.jpg";
NSString *numberString = [userProvidedString stringByDeletingPathExtension];
NSUInteger length = [numberString length];
NSInteger numberLength = 4;
if (length < numberLength)
{
NSLog(#"Error in the string");
return;
}
numberString = [numberString substringWithRange: NSMakeRange(length - 4, 4)];
NSInteger integer = [numberString integerValue];
// Do whatever you want with the integer.
Using Regex(NSRegularExpression in iOS), this can be done very easily,
Check this out,
NSError *error = NULL;
NSString *originalString = #"Splash_10098.jpg";
NSString *regexString = #"([^\?]*_[0-9])([0-9]*)(.)([a-z]*)";
NSRegularExpression* regex = [NSRegularExpression regularExpressionWithPattern:regexString options:NSRegularExpressionCaseInsensitive error:&error];
NSTextCheckingResult *match = [regex firstMatchInString:originalString options:NSRegularExpressionCaseInsensitive range:NSMakeRange(0, [originalString length])];
NSLog(#"FileName: %#", [originalString substringWithRange:[match rangeAtIndex:1]]);
NSLog(#"Total Count: %#", [originalString substringWithRange:[match rangeAtIndex:2]]);
NSLog(#"File type: %#", [originalString substringWithRange:[match rangeAtIndex:4]]);
Result:
FileName: Splash_1
Total Count: 0098
File type: jpg

stringwithformat issue in string searching

I did following experiment. Can any one point out why strings initialized with stringwithformat fail in string searching?
NSString *test1 = #"Hello";
NSString *test2 = #"Hello";
NSString *test3 = [NSString stringWithFormat:#"%# ", test2];
NSRange titleResultsRange = [test1 rangeOfString:test2 options:NSCaseInsensitiveSearch];
I get titleResultsRange.length > 0
But when I do -
NSRange titleResultsRange = [test1 rangeOfString:test3 options:NSCaseInsensitiveSearch];
I get titleResultsRange.length = 0
Why?
Could it be that test3 is "Hello " not "Hello".
NSString *test1 = #"Hello";
NSString *test2 = #"Hello";
NSString *test3 = [NSString stringWithFormat:#"%#", test2];
NSRange titleResultsRange = [test1 rangeOfString:test2 options:NSCaseInsensitiveSearch];
Try now. In your code test3 string contain extra white space.

How to get values after "\n" character?

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];
}