Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I have string this, Total Bill : $22.00, I just want to extract 22 from this string, i'm confused how to get that, I have tried some code but it gives me 2200 rather than 22. My code is this,
NSString * val = #"Total Bill : $22.00";
NSString *newString = [[val componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:#""];
NSLog(#"VV %#",newString);
The simplest is to find the location of the $ and then return the rest of the string. This will give you the 22.00.
NSString *val = #"Total Bill : $22.00";
NSRange dollar = [val rangeOfString:#"$"];
NSRange decimal = [val rangeOfString:#"."];
if (dollar.location != NSNotFound && decimal.location != NSNotFound) {
NSRange range = NSMakeRange(dollar.location + 1, decimal.location - dollar.location - 1)
NSString *amount = [val substringWithRange:range];
NSLog(#"VV %#",amount);
} else {
NSLog(#"No dollar sign or decimal found");
}
One option is to use a NSCharacterSet union with the characters you want to keep (currency separator -- decimal point in your case).. then invert it. Split the string and then join it using this character set. Then you can use NSNumberFormatter to get the result..
NSString *stringToParse = #"Total Blah: $22.00";
NSMutableCharacterSet *characterSet = [NSMutableCharacterSet decimalDigitCharacterSet];
[characterSet formUnionWithCharacterSet:[NSCharacterSet characterSetWithCharactersInString:#".,"]];
stringToParse = [[stringToParse componentsSeparatedByCharactersInSet:[characterSet invertedSet]] componentsJoinedByString:#""];
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setMinimumFractionDigits:0];
[formatter setMaximumFractionDigits:0];
[formatter setPartialStringValidationEnabled:YES];
NSString *str = [formatter stringFromNumber:[formatter numberFromString:stringToParse]];
NSLog(#"%#", str);
You can use NSScanner to extract values like this from a string.
Depending on the type you want, you can use scanDouble:, scanInt: or something else. Here's an example:
NSString *myString = #"Total Bill : $22.00";
NSScanner *scanner = [[NSScanner alloc] initWithString:myString];
// Moves the scanner to the "$" character, then eats that character
[scanner scanUpToString:#"$" intoString:nil];
[scanner scanString:#"$" intoString:nil];
// Here you have options, can scan as a double or an integer, or convert later.
double val = 0;
[scanner scanDouble:&val];
Related
I am new to learning Objective-C (my first programming language!) and trying to write a little program that will add 1 to a number contained within a string. E.g. AA1BB becomes AA2BB.
.
So far I have tried to extract the number and add 1. Then extract the letters and add everything back together in a new string. I have had some success but can't manage to get back to the original arrangement of the initial string.
The code I have so far gives a result of 2BB and disregards the characters before the number which is not what I am after (the result I am trying for with this example would be AA2BB). I can't figure out why!
NSString* aString = #"AA1BB";
NSCharacterSet *numberCharset = [NSCharacterSet characterSetWithCharactersInString:#"0123456789-"]; //Creating a set of Characters object//
NSScanner *theScanner = [NSScanner scannerWithString:aString];
int someNumbers = 0;
while (![theScanner isAtEnd]) {
// Remove Letters
[theScanner scanUpToCharactersFromSet:numberCharset
intoString:NULL];
if ([theScanner scanInt:&someNumbers]) {}
}
NSCharacterSet *letterCharset = [NSCharacterSet characterSetWithCharactersInString:#"ABCDEFGHIJKLMNOPQRSTUVWXYZ"];
NSScanner *letterScanner = [NSScanner scannerWithString:aString];
NSString* someLetters;
while (![letterScanner isAtEnd]) {
// Remove numbers
[letterScanner scanUpToCharactersFromSet:letterCharset
intoString:NULL];
if ([letterScanner scanCharactersFromSet:letterCharset intoString:&someLetters]) {}
}
++someNumbers; //adds +1 to the Number//
NSString *newString = [[NSString alloc]initWithFormat:#"%i%#", someNumbers, someLetters];
NSLog (#"String is now %#", newString);
This is an alternative solution with Regular Expression.
It finds the range of the integer (\\d+ is one or more digits), extracts it, increments it and replaces the value at the given range.
NSString* aString = #"AA1BB";
NSRange range = [aString rangeOfString:#"\\d+" options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
NSInteger numericValue = [aString substringWithRange:range].integerValue;
numericValue++;
aString = [aString stringByReplacingCharactersInRange:range withString:[NSString stringWithFormat:#"%ld", numericValue]];
}
NSLog(#"%#", aString);
I have made an app which the user types in data and it gets a url from google maps like this - [https://www.google.com.au/maps/search/nearest+pizza+shop/#-27.4823545,153.0297855,12z/data=!3m1!4b1
In the middle you see 27.4823545,153.0297855 this is long and lat. So with this I can make my maps work. But I really need to know how to scan this string (the url was made into a string) and get only those numbers, I have already tried this ->
NSString *currentURL = web.request.URL.absoluteString;
string1 = currentURL;
NSScanner *scanner = [NSScanner scannerWithString:string1];
NSString *token = nil;
[scanner scanUpToString:#"#" intoString:NULL];
[scanner scanUpToString:#"z" intoString:&token];
label.text = token;
I think it would be highly likely I did a mistake, since I am new to objective-c, but if there are more effective ways please share . :)
Thanks for all the people who took the time to help.
Bye All!
A solution:
Extrating the path from an NSURL. Then looking at each path components to extract the coordinates components :
NSURL *url = [NSURL URLWithString:#"https://www.google.com.au/maps/search/nearest+pizza+shop/#-27.4823545,153.0297855,12z/data=!3m1!4b1"];
NSArray *components = [url.path componentsSeparatedByString:#"/"];
NSArray *results = nil;
for (NSString *comp in components) {
if ([comp length] > 1 && [comp hasPrefix:#"#"]) {
NSString *resultString = [comp substringFromIndex:1]; // removing the '#'
results = [resultString componentsSeparatedByString:#","]; // lat, lon, zoom
break;
}
}
NSLog(#"results: %#", results);
Will print:
results: (
"-27.4823545",
"153.0297855",
12z
)
This solution gives you a lot of control points for data validation.
Hope this helps.
Edit:
To get rid of the "z". I would treat that as a special number with a number formatter in decimal style and specify that character as the positive and negative suffix:
NSString *targetStr = #"12z";
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.numberStyle = NSNumberFormatterDecimalStyle;
formatter.positiveSuffix = #"z";
formatter.negativeSuffix = #"z";
NSNumber *result = [formatter numberFromString:targetStr];
The var result will contain whatever positive or negative number before the 'z'. You could use a NSScanner to do the trick but I believe it's less flexible.
As a side note, it would be great to get that "z" (zoom's character) from Google's API. If they ever change it to something else your number will still be parsed properly.
I am trying to parse a set of words that contain -- first greek letters, then english letters. This would be easy if there was a delimiter between the sets.That is what I've built so far..
- (void)loadWordFileToArray:(NSBundle *)bundle {
NSLog(#"loadWordFileToArray");
if (bundle != nil) {
NSString *path = [bundle pathForResource:#"alfa" ofType:#"txt"];
//pull the content from the file into memory
NSData* data = [NSData dataWithContentsOfFile:path];
//convert the bytes from the file into a string
NSString* string = [[NSString alloc] initWithBytes:[data bytes]
length:[data length]
encoding:NSUTF8StringEncoding];
//split the string around newline characters to create an array
NSString* delimiter = #"\n";
incomingWords = [string componentsSeparatedByString:delimiter];
NSLog(#"incomingWords count: %lu", (unsigned long)incomingWords.count);
}
}
-(void)parseWordArray{
NSLog(#"parseWordArray");
NSString *seperator = #" = ";
int i = 0;
for (i=0; i < incomingWords.count; i++) {
NSString *incomingString = [incomingWords objectAtIndex:i];
NSScanner *scanner = [NSScanner localizedScannerWithString: incomingString];
NSString *firstString;
NSString *secondString;
NSInteger scanPosition;
[scanner scanUpToString:seperator intoString:&firstString];
scanPosition = [scanner scanLocation];
secondString = [[scanner string] substringFromIndex:scanPosition+[seperator length]];
// NSLog(#"greek: %#", firstString);
// NSLog(#"english: %#", secondString);
[outgoingWords insertObject:[NSMutableArray arrayWithObjects:#"greek", firstString, #"english",secondString,#"category", #"", nil] atIndex:0];
[englishWords insertObject:[NSMutableArray arrayWithObjects:secondString,nil] atIndex:0];
}
}
But I cannot count on there being delimiters.
I have looked at this question. I want something similar. This would be: grab the characters in the string until an english letter is found. Then take the first group to one new string, and all the characters after to a second new string.
I only have to run this a few times, so optimization is not my highest priority.. Any help would be appreciated..
EDIT:
I've changed my code as shown below to make use of NSLinguisticTagger. This works, but is this the best way? Note that the interpretation for english characters is -- for some reason "und"...
The incoming string is: άγαλμα, το statue, only the last 6 characters are in english.
int j = 0;
for (j=0; j<incomingString.length; j++) {
NSString *language = [tagger tagAtIndex:j scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
if ([language isEqual: #"und"]) {
NSLog(#"j is: %i", j);
int k = 0;
for (k=0; k<j; k++) {
NSRange range = NSMakeRange (0, k);
NSString *tempString = [incomingString substringWithRange:range ];
NSLog (#"tempString: %#", tempString);
}
return;
}
NSLog (#"Language: %#", language);
}
Alright so what you could do is use NSLinguisticTagger to find out the language of the word (or letter) and if the language has changed then you know where to split the string. You can use NSLinguisticTagger like this:
NSArray *tagschemes = #[NSLinguisticTagSchemeLanguage];
NSLinguisticTagger *tagger = [[NSLinguisticTagger alloc] initWithTagSchemes:tagschemes options: NSLinguisticTagPunctuation | NSLinguisticTaggerOmitWhitespace];
[tagger setString:#"This is my string in English."];
NSString *language = [tagger tagAtIndex:0 scheme:NSLinguisticTagSchemeLanguage tokenRange:NULL sentenceRange:NULL];
//Loop through each index of the string's characters and check the language as above.
//If it has changed then you can assume the language has changed.
Alternatively you can use NSSpellChecker's requestCheckingOfString to get teh dominant language in a range of characters:
NSSpellChecker *spellChecker = [NSSpellChecker sharedSpellChecker];
[spellChecker setAutomaticallyIdentifiesLanguages:YES];
NSString *spellCheckText = #"Guten Herr Mustermann. Dies ist ein deutscher Text. Bitte löschen Sie diesen nicht.";
[spellChecker requestCheckingOfString:spellCheckText
range:(NSRange){0, [spellCheckText length]}
types:NSTextCheckingTypeOrthography
options:nil
inSpellDocumentWithTag:0
completionHandler:^(NSInteger sequenceNumber, NSArray *results, NSOrthography *orthography, NSInteger wordCount) {
NSLog(#"dominant language = %#", orthography.dominantLanguage);
}];
This answer has information on how to detect the language of an NSString.
Allow me to introduce two good friends of mine.
NSCharacterSet and NSRegularExpression.
Along with them, normalization. (In Unicode terms)
First, you should normalize strings before analyzing them against a character set.
You will need to look at the choices, but normalizing to all composed forms is the way I would go.
This means an accented character is one instead of two or more.
It simplifies the number of things to compare.
Next, you can easily build your own NSCharacterSet objects from strings (loaded from files even) to use to test set membership.
Lastly, regular expressions can achieve the same thing with Unicode Property Names as classes or categories of characters. Regular expressions could be more terse but more expressive.
I have seen this question but it is 2 years old. Is there a better\easier\newer way to check if string has numeric values. e.g 1 or 1.54 or -1 or -1.54 etc etc.
bool status;
NSScanner *scanner;
NSString *testString;
double result;
scanner = [NSScanner scannerWithString:testString];
status = [scanner scanDouble:&result];
status = status && scanner.scanLocation == string.length;
If status == YES then the string is fully numeric.
Or as #Dave points out from this SO answer:
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
number = [formatter numberFromString:string];
status = number != nil;
(I'm not leaking, I'm using ARC :-))
you can use [NSString floatValue]
This may be a easy question but i am not able to find the logic.
I am getting the values like this
12.010000
12.526000
12.000000
12.500000
If i get the value 12.010000 I have to display 12.01
If i get the value 12.526000 I have to display 12.526
If i get the value 12.000000 I have to display 12
If i get the value 12.500000 I have to display 12.5
Can any one help me out please
Thank You
Try this :
[NSString stringWithFormat:#"%g", 12.010000]
[NSString stringWithFormat:#"%g", 12.526000]
[NSString stringWithFormat:#"%g", 12.000000]
[NSString stringWithFormat:#"%g", 12.500000]
float roundedValue = 45.964;
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setMaximumFractionDigits:2];
[formatter setRoundingMode: NSNumberFormatterRoundUp];
NSString *numberString = [formatter stringFromNumber:[NSNumber numberWithFloat:roundedValue]];
NSLog(numberString);
[formatter release];
Some modification you may need-
// You can specify that how many floating digit you want as below
[formatter setMaximumFractionDigits:4];//2];
// You can also round down by changing this line
[formatter setRoundingMode: NSNumberFormatterRoundDown];//NSNumberFormatterRoundUp];
Reference: A query on StackOverFlow
Obviously taskinoor's solution is the best, but you mentioned you couldn't find the logic to solve it... so here's the logic. You basically loop through the characters in reverse order looking for either a non-zero or period character, and then create a substring based on where you find either character.
-(NSString*)chopEndingZeros:(NSString*)string {
NSString* chopped = nil;
NSInteger i;
for (i=[string length]-1; i>=0; i--) {
NSString* a = [string substringWithRange:NSMakeRange(i, 1)];
if ([a isEqualToString:#"."]) {
chopped = [string substringToIndex:i];
break;
} else if (![a isEqualToString:#"0"]) {
chopped = [string substringToIndex:i+1];
break;
}
}
return chopped;
}