Return number from NSString - ios

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

Related

How to add a character at start and end of every word in NSString

Suppose i have this:
NSString *temp=#"its me";
Now suppose i want ' " ' in start and end of every word, how can i achieve it to get the result like this:
"its" "me"
Do i have to use regular expressions?
If you have punctuation inside the string, splitting with a space might not be enough.
Use the word boundary \b: it matches both the leading and trailing word boundaries (that is, it will match an empty space right between word and non-word characters and also at the start/end of the string if followed/preceded with a word character.
NSError *error = nil;
NSString *myText = #"its me";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\b" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate:#"\""];
NSLog(#"%#", modifiedString); // => "its" "me"
See the IDEONE demo
See more details on the regex syntax in Objective C here.
You can do something like,
NSString *str = #"its me";
NSMutableString *resultStr = [[NSMutableString alloc]init];
NSArray *arr = [str componentsSeparatedByString:#" "];
for (int i = 0; i < arr.count; i++) {
NSString *tempStr = [NSString stringWithFormat:#"\"%#\"",arr[i]];
resultStr = [resultStr stringByAppendingString:[NSString stringWithFormat:#"%# ",tempStr]];
}
NSLog(#"result string is : %#",resultStr);
Hope this will help :)

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

Extract one word from a two word string

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

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.

Finding first letter in NSString and counting backwards

I'm new to IOS, and was looking for some guidance.
I have a long NSString that I'm parsing out. The beginning may have a few characters of garbage (can be any non-letter character) then 11 digits or spaces, then a single letter (A-Z). I need to get the location of the letter, and get the substring that is 11 characters behind the letter to 1 character behind the letter.
Can anyone give me some guidance on how to do that?
Example: '!!2553072 C'
and I want : '53072 '
You can accomplish this with the regex pattern: (.{11})\b[A-Z]\b
The (.{11}) will grab any 11 characters and the \b[A-Z]\b will look for a single character on a word boundary, meaning it will be surrounded by spaces or at the end of the string. If characters can follow the C in your example then remove the last \b. This can be accomplished in Objective-C like so:
NSError *error;
NSString *example = #"!!2553072 C";
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:#"(.{11})\\b[A-Z]\\b"
options:NSRegularExpressionCaseInsensitive
error:&error];
if(!regex)
{
//handle error
}
NSTextCheckingResult *match = [regex firstMatchInString:example
options:0
range:NSMakeRange(0, [example length])];
if(match)
{
NSLog(#"match: %#", [example substringWithRange:[match rangeAtIndex:1]]);
}
There may be a more elegant way to do this involving regular expressions or some Objective-C wizardry, but here's a straightforward solution (personally tested).
-(NSString *)getStringContent:(NSString *)input
{
NSString *substr = nil;
NSRange singleLetter = [input rangeOfCharacterFromSet:[NSCharacterSet letterCharacterSet]];
if(singleLetter.location != NSNotFound)
{
NSInteger startIndex = singleLetter.location - 11;
NSRange substringRange = NSMakeRange(start, 11);
substr = [tester substringWithRange:substringRange];
}
return substr;
}
You can use NSCharacterSets to split up the string, then take the first remaining component (consisting of your garbage and digits) and get a substring of that. For example (not compiled, not tested):
- (NSString *)parseString:(NSString *)myString {
NSCharacterSet *letters = [NSCharacterSet letterCharacterSet];
NSArray *components = [myString componentsSeparatedByCharactersInSet:letters];
assert(components.count > 0);
NSString *prefix = components[0]; // assuming relatively new Xcode
return [prefix substringFromIndex:(prefix.length - 11)];
}
//to get rid of all non-Digits in a NSString
NSString *customerphone = CustomerPhone.text;
int phonelength = [customerphone length];
NSRange customersearchRange = NSMakeRange(0, phonelength);
for (int i =0; i < phonelength;i++)
{
const unichar c = [customerphone characterAtIndex:i];
NSString* onechar = [NSString stringWithCharacters:&c length:1];
if(!isdigit(c))
{
customerphone = [customerphone stringByReplacingOccurrencesOfString:onechar withString:#"*" options:0 range:customersearchRange];
}
}
NSString *PhoneAllNumbers = [customerphone stringByReplacingOccurrencesOfString:#"*" withString:#"" options:0 range:customersearchRange];

Resources