我想只在字符串包含数字的情况下将字符串中的数字和字符分开,否则我不想将其拆分。
例如:
String1 = @"hai 1234";
我想将此字符串拆分为
String2 = 1234
String3 = hai;
另一个例子:
String1 = @"hai"
我不想分手。
答案 0 :(得分:0)
使用以下代码拆分Characters
& Numbers
//Numbers
NSString *numbers = [@"hai 1234" stringByTrimmingCharactersInSet:[NSCharacterSet letterCharacterSet]];
//Characters
NSString *characters = [@"hai 1234" stringByTrimmingCharactersInSet:[NSCharacterSet decimalDigitCharacterSet]];
答案 1 :(得分:0)
这个问题是重复的。 Objective-C: Find numbers in string
// Input
NSString *originalString = @"This is my string. #1234";
// Intermediate
NSString *numberString;
NSScanner *scanner = [NSScanner scannerWithString:originalString];
NSCharacterSet *numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
// Throw away characters before the first number.
[scanner scanUpToCharactersFromSet:numbers intoString:NULL];
// Collect numbers.
[scanner scanCharactersFromSet:numbers intoString:&numberString];
// Result.
int number = [numberString integerValue];
// Text
NSString *text = [originalString stringByReplacingOccurrencesOfString:numberString withString:@""];
答案 2 :(得分:0)
//number
NSString *onlyNumbers = [[string1 componentsSeparatedByCharactersInSet:
[[NSCharacterSet decimalDigitCharacterSet] invertedSet]]
componentsJoinedByString:@""];
//characters
NSString *onlyCharacters = [[string1 componentsSeparatedByCharactersInSet:
[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:@""];