我有几根琴弦。有些开头有空格,有些则没有。我想检查字符串是否以空格开头,如果是,请将其删除。
Answers:
NSString类中有针对该方法的方法。检查stringByTrimmingCharactersInSet:(NSCharacterSet *)set
。您应该使用以下[NSCharacterSet whitespaceCharacterSet]
参数:
NSString *foo = @" untrimmed string ";
NSString *trimmed = [foo stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
stringByTrimmingCharactersInSet
仅删除字符串开头和结尾的字符,而不删除中间的字符。对于那些试图在字符串中间删除空格的人,请使用[yourString stringByReplacingOccurrencesOfString:@" " withString:@""]
。
您可以将stringByTrimmingCharactersInSet NSString方法与whitespaceAndNewlineCharacterSet NSCharacterSet结合使用,如下所示:
NSString *testString = @" Eek! There are leading and trailing spaces ";
NSString *trimmedString = [testString stringByTrimmingCharactersInSet:
[NSCharacterSet whitespaceAndNewlineCharacterSet]];
这将仅删除前导空白。
NSString *myString = @" 123 ";
NSLog(@"mystring %@, length %d",myString, myString.length);
NSRange range = [myString rangeOfString:@"^\\s*" options:NSRegularExpressionSearch];
myString = [myString stringByReplacingCharactersInRange:range withString:@""];
NSLog(@"mystring %@, length %d",myString, myString.length);
输出
mystring 123 , length 9
mystring 123 , length 6