iOS nsscanner scan string to get the appropriate string

Source: Internet
Author: User

For example, extracting numbers from a string

-(int) findnumfromstr
{
NSString *originalstring = @ "a1b2c3d4e5f6g7h8i9j";

Intermediate
nsmutablestring *numberstring = [[[[Nsmutablestring alloc] init] autorelease];
NSString *tempstr;
Nsscanner *scanner = [Nsscanner scannerwithstring:originalstring];
Nscharacterset *numbers = [Nscharacterset charactersetwithcharactersinstring:@ "0123456789"];

while (![ Scanner Isatend]) {
Throw away characters before the first number.
[Scanner scanuptocharactersfromset:numbers intostring:null];

Collect numbers.
[Scanner Scancharactersfromset:numbers intostring:&tempstr];
[Numberstring APPENDSTRING:TEMPSTR];
TempStr = @ "";
}
Result.
int number = [Numberstring integervalue];

return number;
}


Here are some of the interfaces and explanations I have found about Nsscanner: (reproduced below)

Nsscanner is a class that is used to scan a string for specified characters, especially translating/converting them to numbers and other strings. You can specify the string property of Nsscaner when you create it, and then scanner will scan each character of the string from start to finish as you ask.

Create a scanner

Nsscanner is a class family, and Nsscanner is a kind of public. In general, you can initialize a scanner with the scannerwithstring: or localizedscannerwithstring: Method. Both methods return a scanner object and initialize its string property with the string parameter that you pass. the scanner object points to the beginning of the string when it was first created. The scanner method begins scanning, such as scanint:,scandouble:,scanstring:intostring:. If you want to scan multiple times, you usually need to use the while loop,

For example, the following code shows:

?
1234567891011 floataFloat;      NSScanner *theScanner = [NSScanner scannerWithString:aString];     while ([theScanner isAtEnd] == NO) {           [theScanner scanFloat:&aFloat];         // implementation continues...    }


The above example loops through the floating-point values in the search string and assigns a value to the afloat parameter. At this point, the isatend will follow the last character position searched to see if the next floating-point value exists until the end of the scan. The core of the scanning action is the change of position. The location continues to move through the scan until the end of the scan.

Alternatively, you can set whether the case is ignored by using the Setcasesensitive: method, which is ignored by default.

Use of scanner

The scan operation starts at the location of the last scan and continues to be scanned until the specified content appears (if any).

Take the string "137 small cases of bananas" as an example, after scanning an integer, the position of scanner becomes 3, which is the space after the number. Usually, you will continue to scan and skip characters that you do not care about. Then you can use the Setscanlocation: method to skip a certain number of characters (you can also use this method to re-scan a part of a string after some errors have occurred). If you want to skip characters in a particular character set, you can use the setcharacterstobeskipped: method. Scanner will not start until any scan operation has skipped whitespace characters. But when it finds a character that can be scanned, it uses all the characters to match the specified content. Scanner whitespace characters and line breaks are ignored by default. note that for ignoring characters, it is always case-sensitive. For example, to ignore all the original letters, you must use "Aeiouaeiou" instead of just "Aeiou" or "Aeiou".

If you want to get the contents of a string in the current position, you can use the Scanuptostring:intostring: Method (You can pass a null to the 2nd argument if you do not want to keep the characters).

For example, take the following string as an example:

137 Small cases of bananas

The following code can find the packing specification (small cases) and the number of packages (137) from the string.

?
1234567 NSString *bananas = @"137 small cases of bananas"NSString *separatorString = @" of"NSScanner *aScanner = [NSScanner scannerWithString:bananas];   NSInteger anInteger; [aScanner scanInteger:&anInteger]; NSString *container; [aScanner scanUpToString:separatorString intoString:&container];


Finding the string separatorstring is significant for the "of" relationship. The default scanner ignores whitespace characters, so spaces after the number 137 are ignored. But when scanner begins with the character that follows the space, all the characters are added to the output string until the search string ("of") is encountered.

If the search string is "of" (preceded by No spaces), the first value of container should be "smallcases" (followed by a space), and if the search string is "of" (preceded by a space), the 1th value of container is "small cases" (no space behind).

after scanning to the specified string (the search string), the location of the scanner points to the beginning of the string. If you want to continue scanning for characters after the string, you must first scan the specified string (the search string). The following code shows how to skip the search string and get the product type. Note that we used the Substringfromindex:, which is equivalent to continuing the scan until the end of the entire string.

?
12345 [aScanner scanString:separatorString intoString:NULL]; NSString *product; product = [[aScanner string] substringFromIndex:[aScanner scanLocation]]; // could also use: // product = [bananas substringFromIndex:[aScanner scanLocation]];

Example:

Suppose you have the following string:

Product:acme Potato Peeler; cost:0.98 73
Product:chef Pierre Pasta Fork; cost:0.75 19
Product:chef Pierre Colander; cost:1.27 2

The following code demonstrates the operation of reading the product name and price (the price is simply read as a float), skipping the "Product:" and "Cost:" substrings, as well as semicolons. Note that because scanner ignores whitespace and newline characters by default, no processing is specified in the loop (especially for the integer at the end of the read, which does not require processing additional whitespace characters).

?
123456789101112131415161718192021222324252627282930313233343536373839404142 NSString *string = @"Product: Acme Potato Peeler; Cost:0.98 73\n\ Product: Chef Pierre Pasta Fork; Cost:0.75 19\n\ Product: Chef Pierre Colander; Cost:1.27 2\n";    NSCharacterSet *semicolonSet; NSScanner *theScanner;    NSString *PRODUCT = @"Product:"NSString *COST = @"Cost:"   NSString *productName; float productCost;  NSInteger productSold;     semicolonSet = [NSCharacterSet characterSetWithCharactersInString:@";"]; theScanner = [NSScanner scannerWithString:string];    while ([theScanner isAtEnd] == NO)            if([theScanner scanString:PRODUCT intoString:NULL] &&             [theScanner scanUpToCharactersFromSet:semicolonSet                intoString:&productName] &&            [theScanner scanString:@";"intoString:NULL] &&             [theScanner scanString:COST intoString:NULL] &&            [theScanner scanFloat:&productCost] &&            [theScanner scanInteger:&productSold])                   NSLog(@"Sales of %@: $%1.2f", productName, productCost * productSold);           }


Localization

Scanner supports localized scanning, which allows you to specify languages and dialects. Nsscanner only use the locale attribute on the decimal separator (with Nsdecimalseparator as key). You can use lcoalizedscannerwithstring: to create a scanner of the specified locale, or to specify the locale property of the scanner with the setlocale: method display. If you do not specify Locale,scanner assume that the default locale is used.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

iOS nsscanner scan string to get the appropriate string

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.