如何在 NSString 中的每个单词的开头和结尾添加一个字符
How to add a character at start and end of every word in NSString
假设我有这个:
NSString *temp=@"its me";
现在假设我想在每个单词的开头和结尾使用“”,我怎样才能得到这样的结果:
"its" "me"
我必须使用正则表达式吗?
你可以这样做,
NSString *str = @"its me";
NSMutableString *resultStr = [[NSMutableString alloc]init];
NSArray *arr = [str componentsSeparatedByString:@" "];
for (int i = 0; i < arr.count; i++) {
NSString *tempStr = [NSString stringWithFormat:@"\"%@\"",arr[i]];
resultStr = [resultStr stringByAppendingString:[NSString stringWithFormat:@"%@ ",tempStr]];
}
NSLog(@"result string is : %@",resultStr);
希望这会有所帮助:)
如果字符串中有标点符号,用 space 分隔可能不够。
使用word boundary \b
:它匹配前导和尾随的单词边界(也就是说,它将匹配单词和非单词字符之间的空 space 右边以及 start/end 的字符串如果 followed/preceded 带有单词字符。
NSError *error = nil;
NSString *myText = @"its me";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\b" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate:@"\""];
NSLog(@"%@", modifiedString); // => "its" "me"
在 regex syntax in Objective C here 上查看更多详细信息。
假设我有这个:
NSString *temp=@"its me";
现在假设我想在每个单词的开头和结尾使用“”,我怎样才能得到这样的结果:
"its" "me"
我必须使用正则表达式吗?
你可以这样做,
NSString *str = @"its me";
NSMutableString *resultStr = [[NSMutableString alloc]init];
NSArray *arr = [str componentsSeparatedByString:@" "];
for (int i = 0; i < arr.count; i++) {
NSString *tempStr = [NSString stringWithFormat:@"\"%@\"",arr[i]];
resultStr = [resultStr stringByAppendingString:[NSString stringWithFormat:@"%@ ",tempStr]];
}
NSLog(@"result string is : %@",resultStr);
希望这会有所帮助:)
如果字符串中有标点符号,用 space 分隔可能不够。
使用word boundary \b
:它匹配前导和尾随的单词边界(也就是说,它将匹配单词和非单词字符之间的空 space 右边以及 start/end 的字符串如果 followed/preceded 带有单词字符。
NSError *error = nil;
NSString *myText = @"its me";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\b" options:NSRegularExpressionCaseInsensitive|NSRegularExpressionAnchorsMatchLines error:&error];
NSString *modifiedString = [regex stringByReplacingMatchesInString:myText options:0 range:NSMakeRange(0, [myText length]) withTemplate:@"\""];
NSLog(@"%@", modifiedString); // => "its" "me"
在 regex syntax in Objective C here 上查看更多详细信息。