Extract one word from a two word string - ios

I have a two word string in another view controller containing a user defined first and last name
NSString *userName = ([self hasAttributeWithName:kContractorName] ? [self attributeWithName:kContractorName].value : [self.certificate.contractor.name uppercaseString]);
when retrieving this string in another view controller I want to extract only the first name.
I researched SO on using scanner and found a very helpful answer here: Objective C: How to extract part of a String (e.g. start with '#'), and im almost there.
The problem is I can only seem extract the second name with my variation on the origial code. Im scanning my string up to the space between first and second name, this returns the second name fine. Just need a nudge now on how to set this to extract the first name instead of the second
NSMutableArray *substrings = [NSMutableArray new];
NSScanner *scanner = [NSScanner scannerWithString:userName];
[scanner scanUpToString:#" " intoString:nil]; // Scan all characters before
while(![scanner isAtEnd]) {
NSString *name = nil;
[scanner scanString:#" " intoString:nil]; // Scan the character
if([scanner scanUpToString:#" " intoString:&name]) {
// If the space immediately followed the , this will be skipped
[substrings addObject:name];
}
[scanner scanUpToString:#" " intoString:nil]; // Scan all characters before next
}

Better use NSString's componentsSeparatedByString method:
NSString* firstName = [userName componentsSeparatedByString:#" "][0];

If first and last name are separated with a space you can use:
NSArray *terms = [userName componentsSeparatedByString:#" "];
NSString *firstName = [terms objectAtIndex:0];

You could just split the string into first and last names using componentsSeparatedByString.
NSArray *subStrings = [userName componentsSeparatedByString:#" "];
NSString *firstName = [subStrings objectAtIndex:0];

Sure, you can just split the string by spaces and take the first element, but where’s the fun in that? Try NSLinguisticTagger to actually split this using a Cocoa API:
__block NSString *firstWord = nil;
NSString *question = #"What is the weather in San Francisco?";
NSLinguisticTaggerOptions options = NSLinguisticTaggerOmitWhitespace | NSLinguisticTaggerOmitPunctuation | NSLinguisticTaggerJoinNames;
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes: [NSLinguisticTagger availableTagSchemesForLanguage:#"en"] options:options];
tagger.string = question;
[tagger enumerateTagsInRange:NSMakeRange(0, [question length]) scheme:NSLinguisticTagSchemeNameTypeOrLexicalClass options:options usingBlock:^(NSString *tag, NSRange tokenRange, NSRange sentenceRange, BOOL *stop) {
firstWord = [question substringWithRange:tokenRange];
*stop = YES;
}];

Related

Extract a String out of a specific set of strings

I have a text as:
sometext[string1 string2]someText
I want to retrieve string1 and string2 as separate strings from this text
How can i parse it in objective - c?
i have found the solution
NSArray *arrayOne = [prettyFunctionString componentsSeparatedByString:#"["];
NSString *parsedOne = [arrayOne objectAtIndex:1];
NSArray *arrayTwo = [parsedOne componentsSeparatedByString:#"]"];
NSString *parsedTwo = [arrayTwo objectAtIndex:0];
NSArray *arrayThree = [parsedTwo componentsSeparatedByString:#" "];
NSString *className = [arrayThree objectAtIndex:0];
NSString *functionName = [arrayThree objectAtIndex:1];
thanks anyways
Maybe something like this could work for you
NSString * string = #"sometext[string1 string2]sometext";
NSString * pattern = #"(.*)\[(.+) (.+)\](.*)"
NSRegularExpression * expression = [NSRegularExpression regularExpressionWithPattern:pattern options:NSRegularExpressionCaseInsensitive error:NULL];
NSTextCheckingResult * match = [expression firstMatchInString:string options:NSMatchingReportCompletion range:NSMakeRange(0, string.length)];
if (match) {
NSString * substring1 = [string substringWithRange:[match rangeAtIndex:2]];
NSString * substring2 = [string substringWithRange:[match rangeAtIndex:3]];
// do something with substring1 and substring2
}
You can Use this Simple Approach approach
NSString *str = #"sometext[string1 string2]someText";
NSInteger loc1 = [str localizedStandardRangeOfString:#"["].location;
NSInteger loc2 = [str localizedStandardRangeOfString:#"]"].location;
NSString *resultString = [str substringWithRange:(NSRange){loc1+1,loc2-loc1}];
NSArray *resultArry = [resultString componentsSeparatedByString:#" "];
result array will contain your required Reuslt
For completeness - if you are trying to extract strings out of a string with a known pattern, then an NSScanner is the way to go.
This goes through the string in one pass.
NSString *string = #"sometext[string1 string2]someText";
NSScanner *scanner = [NSScanner scannerWithString:string];
NSString *str1;
NSString *str2;
[scanner scanUpToString:#"[" intoString:nil]; // Scan up to the '[' character.
[scanner scanString:#"[" intoString:nil]; // Scan the '[' character and discard it.
[scanner scanUpToCharactersFromSet:[NSCharacterSet whitespaceCharacterSet] intoString: &str1]; // Scan all the characters up to the whitespace and accumulate the characters into 'str1'
[scanner scanUpToCharactersFromSet:[NSCharacterSet alphanumericCharacterSet] intoString:nil]; // Scan up to the next alphanumeric character and discard the result.
[scanner scanUpToString:#"]" intoString:&str2]; // Scan up to the ']' character, accumulate the characters into 'str2'
// Log the output.
NSLog(#"First String: %#", str1);
NSLog(#"Second String: %#", str2);
Which puts the output into the console of:
2015-09-23 11:31:02.522 StringExtractor[46678:4289499] First String: string1
2015-09-23 11:31:02.522 StringExtractor[46678:4289499] Second String: string2

iOS - String capitalisation when followed by a numeric

I have a requirement where in first letter of all words in a sentence need to be capitalised. I achieved this through the below code
myString = [myString capitalizedString];
But there is an issue with this.. if the word starts with a numeric for eg "32abc", after capitalisation it changes to "32Abc". I need it to be "32abc".
Help would be appreciated.
Method 1
NSString *input = #"32abc";
/* get first char */
NSString *firstChar = [input substringToIndex:1];
/* remove any diacritic mark */
NSString *folded = [firstChar stringByFoldingWithOptions:NSDiacriticInsensitiveSearch locale:[NSLocale currentLocale]];
/* create the new string */
NSString *capitalisedSentence = [[folded uppercaseString] stringByAppendingString:[input substringFromIndex:1]];
Method 2 (Optimized)
NSString *input = #"32abc";
NSString *capitalisedSentence = [input stringByReplacingCharactersInRange:NSMakeRange(0,1)
withString:[[input substringToIndex:1] capitalizedString]];
Try this:
myString = [myString stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:[[myString substringToIndex:1] uppercaseString]];

IOS NSString get characters before '#"

for example i have string like this:
NSString *one = B3#This is the first string
NSString *two = 1#This is the second string
How can i get the "B3" and "1" Character only (using objective C)
Thanks..
Turns out this is one way to do it:
NSRange range = [one rangeOfString:#"#" options:NSBackwardsSearch];
NSString *newString = [one substringToIndex:range.location];
Thanks for all the answers.
NSString* one = #"B3#";
NSString* two = #"1#";
NSString* result = [one stringByReplacingOccurrencesOfString:#"#" withString:#""];
NSString* result_2 = [two stringByReplacingOccurrencesOfString:#"#" withString:#""];
//if you need to marge
NSString* tot = [NSString stringWithFormat:#"%#%#",result,result_2];

Extract substring from a string in iOS?

Is there any way to extract substring from a string like below
My real string is "NS09A" or "AB455A" but i want only "NS09" or "AB455" (upto the end of numeric part of original string).
How can i extract this?
I saw google search answers like using position of starting and endinf part of substring we can extract that ,But here any combination of "Alphabets+number+alphabets" .I need only " "Alphabets+number"
Perhaps not everybody will agree, but I like regular expressions. They allow to specify
precisely what you are looking for:
NSString *string = #"AB455A";
// One or more "word characters", followed by one or more "digits":
NSString *pattern = #"\\w+\\d+";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern
options:0
error:NULL];
NSTextCheckingResult *match = [regex firstMatchInString:string
options:NSMatchingAnchored
range:NSMakeRange(0, [string length])];
if (match != nil) {
NSString *extracted = [string substringWithRange:[match range]];
NSLog(#"%#", extracted);
// Output: AB455
} else {
// Input string is not of the expected form.
}
Try This:-
NSString *str=#"ASRF12353FYTEW";
NSString *resultStr;
for(int i=0;i<[str length];i++){
NSString *character = [str substringFromIndex: [str length] - i];
if([character intValue]){
resultStr=[str substringToIndex:[str length]-i+1];
break;
}
}
NSLog(#"RESUKT STRING %#",resultStr);
I tested this code:
NSString *originalString = #"NS09A";
// Intermediate
NSString *numberString;
NSString *numberString1;
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:#"0123456789"];
[scanner scanUpToCharactersFromSet:numbers intoString:&numberString];
[scanner scanCharactersFromSet:numbers intoString:&numberString1];
NSString *result=[NSString stringWithFormat:#"%#%#",numberString,numberString1];
NSLog(#"Finally ==%#",result);
Hope it Help You
OUTPUT
Finally ==NS09
UPDATE:
NSString *originalString = #"kirtimali#gmail.com";
NSString *result;
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *cs1 = [NSCharacterSet characterSetWithCharactersInString:#"#"];
[scanner scanUpToCharactersFromSet:cs1 intoString:&result];
NSLog(#"Finally ==%#",result);
output:
Finally ==kirtimali
Use NSScanner and the scanUpToCharactersFromSet:intoString: method to specify which characters should be used to stop the parsing. This could be in a loop with some logic or it could be applied in conjunction with setScanLocation: if you already have a method of finding the start of each section you want to extract.
When using scanUpToCharactersFromSet:intoString: you are looking for the next invalid character. It doesn't need to be a 'special' character (in a unicode sense), just a known set of characters that aren't valid for the content you want. So, you might use:
[[NSCharacterSet characterSetWithCharactersInString:#"1234567890"] invertedSet]
You can use - (NSString *)substringWithRange:(NSRange)aRange method on NSString class to get a substring extracted. Use NSMakeRange to create the NSRange object.

Return number from NSString

I have NSString like this: #"text 932".
How I can return number from this string. Number is always at the end of string, but i can' t use stringWithRange, because number don' t have constant length. So I'm seeking for better method.
I aslo want' know how to return number from string like this #"text 3232 text". I aslo don' t know position of number.
There is any function that find number in string ?
Here is a solution that will work for both strings
NSString *myString = #"text 3232 text";
//Create a scanner with the string
NSScanner *scanner = [NSScanner scannerWithString:myString];
//Create a character set that includes all letters, whitespaces, and newlines
//These will be used as skip tokens
NSMutableCharacterSet *charactersToBeSkipped = [[NSMutableCharacterSet alloc]init];
[charactersToBeSkipped formUnionWithCharacterSet:[NSCharacterSet letterCharacterSet]];
[charactersToBeSkipped formUnionWithCharacterSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[scanner setCharactersToBeSkipped:charactersToBeSkipped];
[charactersToBeSkipped release];
//Create an int to hold the number
int i;
//Do the work
if ([scanner scanInt:&i]) {
NSLog(#"i = %d", i);
}
The output of the NSLog is
i = 3232
EDIT
To handle decimals:
float f;
if ([scanner scanFloat:&f]) {
NSLog(#"f = %f", f);
}
Update:
Updated to test whether there is a match or not, and also to handle negative/decimal numbers
NSString *inputString=#"text text -9876.234 text";
NSString *regExprString=#"-{0,1}\\d*\\.{0,1}\\d+";
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:regExprString options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:nil];
NSRange rangeOfFirstMatch=[regex firstMatchInString:inputString options:0 range:NSMakeRange(0, inputString.length)].range;
if(rangeOfFirstMatch.length>0){
NSString *firstMatch=[inputString substringWithRange:rangeOfFirstMatch];
NSLog(#"firstmatch:%#",firstMatch);
}
else{
NSLog(#"No Match");
}
Original:
Here is a solution that uses regular expressions:
NSString *inputString=#"text text 0123456 text";
NSString *regExprString=#"[0-9]+";
NSRegularExpression * regex = [NSRegularExpression regularExpressionWithPattern:regExprString options:NSRegularExpressionCaseInsensitive|NSRegularExpressionDotMatchesLineSeparators error:nil];
NSString *firstMatch=[inputString substringWithRange:[regex firstMatchInString:inputString options:0 range:NSMakeRange(0, inputString.length)].range];
NSLog(#"%#",firstMatch);
output is:
0123456
If you want an actual integer from that, you can add:
NSInteger i=[firstMatch integerValue];
NSLog(#"%d",i);
Output is then: 123456

Resources