How would I Find a Word, and Take all characters after the first occurrence of the word, but stop after an occurrence of a different word? - objective-c

For instance
NSString *string = #"I need help finding a string";
NSString *newString = #"need";
I would need this to work not only to work for this string. An example would be to take a string and remove everything after the word "I " and before the word " help".
Thank you very much!
Moved from a comment for legibility:
NSString *string = #"I need help finding a string";
NSRange rr2 = [TWEET rangeOfString:#"I "];
NSRange rr3 = [TWEET rangeOfString:#" help"];
int lengt = rr3.location - rr2.location;
int location = rr2.location + rr2.length;
NSRange aa;
aa.location = location;
aa.length = lengt;
NSString *link;
link = [TWEET substringWithRange:aa];
NSLog(#"The link is %#", link);

One way would be to split the string into single words, and iterate through it, first searching for the first word, while adding every word to a new string until you found it and the searching for the second word and after you found that just add the remaining words.
This could look like this in code:
NSString *myString = #"I need help finding a string";
NSString *firstWord = #"need";
NSString *secondWord = #"a";
NSMutableString *newString = [NSMutableString stringWithString:#""];
int index = 0;
for (NSString *word in [myString componentsSeparatedByString:#" "]) {
if(index == 0) {
if([word isEqualToString:firstWord])
index = 1;
[newString appendFormat:#"%# ", word];
}
else if(index == 1) {
if([word isEqualToString:secondWord])
index = 2;
}
else
[newString appendFormat:#"%# ", word];
}

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

Formatting a String in Objective - C

I'm getting a response from webservice as a string like below one -
brand=company%%samsung##modelnumber=webmodel%%GT1910##Sim=Single%%SingleSim##3g=yes%%Yes##wifi=yes%%yes(2.1 mbps upto)
I'm confusing that to format my response like below one -
brand=samsung
modelnumber=GT1910
Sim=SingleSim
3g=Yes
wifi=(2.1 mbps upto)
I've tried to remove the special characters (## and %%)
specialString = [specialString stringByReplacingOccurrencesOfString:#"##" withString:#"\n"];
specialString = [specialString stringByReplacingOccurrencesOfString:#"%%" withString:#"\n"];
specialString= [specialString stringByReplacingOccurrencesOfString:#" " withString:#""];
My output was -
brand=company
samsung
modelnumber=webmodel
GT1910
Sim=Single
SingleSim
3g=yes
Yes
wifi=yes
(2.1 mbps upto)
How to remove unwanted words.
You can't use simple find and replace because there are parts of the original string you don't want.
Untested, but this will probably work:
NSArray *parts = [specialstring componentsSeparatedByString:#"##"];
NSMutableArray *result = [[NSMutableArray alloc] init];
for(NSString *piece in parts) {
NSArray *pairs = [piece componentsSeparatedByString:#"="];
if([pairs count] > 1) {
NSString *key = [pairs objectAtIndex:0];
NSString *values = [pairs objectAtIndex:1];
NSArray *avalues = [values componentsSeparatedByString:#"%%"];
[result addObject:[NSString stringWithFormat:#"%#=%#", key, [avalues lastObject]]];
}
}
NSLog(#"%#", [result componentsJoinedByString:#"\n"]);
// [result release]; // Uncomment if ARC is turned off
First splits by ## and iterates over array. Then splits by = to get key on left side (index 0). Takes right side (index 1) and splits by %% and uses last value.
Trim like below it will work
NSString *strRes = #"brand=company%%samsung##modelnumber=webmodel%%GT1910##Sim=Single%%SingleSim##3g=yes%%Yes##wifi=yes%%yes(2.1 mbps upto)";
strRes = [strRes stringByReplacingOccurrencesOfString:#"=" withString:#"--"];
strRes = [strRes stringByReplacingOccurrencesOfString:#"##" withString:#"\n"];
NSRange rangeForTrim;
while ((rangeForTrim = [strRes rangeOfString:#"--[^%%]+%%" options:NSRegularExpressionSearch]).location != NSNotFound)
strRes = [strRes stringByReplacingCharactersInRange:rangeForTrim withString:#"="];
NSLog(#"%#",strRes);
Well, I can't write the code right away but here's what you gotta do:
Replace all %% with (space)
Replace all ## with \n
Remove all words between = and (space)

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

How to get the first N words from a NSString in Objective-C?

What's the simplest way, given a string:
NSString *str = #"Some really really long string is here and I just want the first 10 words, for example";
to result in an NSString with the first N (e.g., 10) words?
EDIT: I'd also like to make sure it doesn't fail if the str is shorter than N.
If the words are space-separated:
NSInteger nWords = 10;
NSRange wordRange = NSMakeRange(0, nWords);
NSArray *firstWords = [[str componentsSeparatedByString:#" "] subarrayWithRange:wordRange];
if you want to break on all whitespace:
NSCharacterSet *delimiterCharacterSet = [NSCharacterSet whitespaceAndNewlineCharacterSet];
NSArray *firstWords = [[str componentsSeparatedByCharactersInSet:delimiterCharacterSet] subarrayWithRange:wordRange];
Then,
NSString *result = [firstWords componentsJoinedByString:#" "];
While Barry Wark's code works well for English, it is not the preferred way to detect word breaks. Many languages, such as Chinese and Japanese, do not separate words using spaces. And German, for example, has many compounds that are difficult to separate correctly.
What you want to use is CFStringTokenizer:
CFStringRef string; // Get string from somewhere
CFLocaleRef locale = CFLocaleCopyCurrent();
CFStringTokenizerRef tokenizer = CFStringTokenizerCreate(kCFAllocatorDefault, string, CFRangeMake(0, CFStringGetLength(string)), kCFStringTokenizerUnitWord, locale);
CFStringTokenizerTokenType tokenType = kCFStringTokenizerTokenNone;
unsigned tokensFound = 0, desiredTokens = 10; // or the desired number of tokens
while(kCFStringTokenizerTokenNone != (tokenType = CFStringTokenizerAdvanceToNextToken(tokenizer)) && tokensFound < desiredTokens) {
CFRange tokenRange = CFStringTokenizerGetCurrentTokenRange(tokenizer);
CFStringRef tokenValue = CFStringCreateWithSubstring(kCFAllocatorDefault, string, tokenRange);
// Do something with the token
CFShow(tokenValue);
CFRelease(tokenValue);
++tokensFound;
}
// Clean up
CFRelease(tokenizer);
CFRelease(locale);
Based on Barry's answer, I wrote a function for the sake of this page (still giving him credit on SO)
+ (NSString*)firstWords:(NSString*)theStr howMany:(NSInteger)maxWords {
NSArray *theWords = [theStr componentsSeparatedByString:#" "];
if ([theWords count] < maxWords) {
maxWords = [theWords count];
}
NSRange wordRange = NSMakeRange(0, maxWords - 1);
NSArray *firstWords = [theWords subarrayWithRange:wordRange];
return [firstWords componentsJoinedByString:#" "];
}
Here's my solution, derived from the answers given here, for my own problem of removing the first word from a string...
NSMutableArray *words = [NSMutableArray arrayWithArray:[lowerString componentsSeparatedByString:#" "]];
[words removeObjectAtIndex:0];
return [words componentsJoinedByString:#" "];