stringwithformat issue in string searching - objective-c

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.

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:#" "]];
}

regex for adding a space between two words if not already there

I would like to add a spacing between two words if its already not there:
//Sample 1
NSString *word1 = #"First";
NSString *word2 = #"Word";
NSString *output = [NSString stringWithFormat:#"%#%#", word1, word2];
//output = FirstWord --> I want "First Word"
If there is already a space "First " then it should not add another one.
Just trim the first string, and then always put a space.
NSString *word1 = #"First";
NSString *word2 = #"Word";
NSString *word1Trimmed = [string stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceCharacterSet]];
NSString *output = [NSString stringWithFormat:#"%# %#", word1Trimmed, word2];

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);

How to get substring of NSString?

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);