![](/img/trans.png)
[英]What's the best way to trim whitespace from a string in Cocoa Touch?
[英]Trim whitespace in between characters
我刚刚更新为ios 7 sdk,我想修剪/替换字符串字符之间的空格,从而从ABAddressBook中取出数字。
我曾尝试使用下面的代码替换“”,但此代码在ios7 sdk中似乎不起作用,顺便说一下,它在ios 6 sdk中工作正常。
NSString *TrimmedNumberField = [self.numberField.text
stringByReplacingOccurrencesOfString:@" " withString:@""];
在IOS 7中还有其他方法可以做到吗?
编辑:
我正在尝试的电话号码类型。
输入: "+65 12 345 6789"
我从NSLog获得的输出是" 12 345 6789"
我意识到,当我添加到NSDictionary中并在NSLog中查看它时,它似乎包含\\ u00a0的unix代码表示,类似于“中间的点”,不等于句号。
提前致谢。
从这里找到答案
phoneNumber = [phoneNumber stringByReplacingOccurencesOfString:@"." withString:@""];
//其中@“。 是通过键入Option + 空格键创建的
该号码是从ABAddressbook中提取的。
您可以遍历字符串并删除空格,只要有
NSString *someString = @"A string with multiple spaces and other whitespace.";
NSMutableString *mutableCopy = [someString mutableCopy];
// get first occurance of whitespace
NSRange range = [mutableCopy rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
// If there is a match for the whitespace ...
while (range.location != NSNotFound) {
// ... delete it
[mutableCopy deleteCharactersInRange:range];
// and get the next whitespace
range = [mutableCopy rangeOfCharacterFromSet:[NSCharacterSet whitespaceCharacterSet]];
}
// no more whitespace. You can get back to an immutable string
someString = [mutableCopy copy];
上面的字符串的结果是Astringwithmultiplespacesandotherwhitespace.
尝试这个:
NSString *str = @" untrimmed string ";
NSString *trimmed = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
尝试这个
[yourString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
whitespaceCharacterSet iOS的Apple文档说
返回以二进制格式编码接收器的NSData对象。
讨论此格式适合于保存到文件或以其他方式传输或存档。
字符集的原始位图表示形式是2 ^ 16位(即8192字节)的字节数组。 位置n的位的值表示十进制Unicode值n的字符存在于字符集中。 要测试原始位图表示中是否存在带十进制Unicode值n的字符,请使用以下表达式:
所以试试这个
NSString *testString = @" Eek! There are leading and trailing spaces ";
NSString *trimmedString = [testString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.