我的应用程序在":“之后放了一个空格,以防用户忘记。就像这样:
input = [input stringByReplacingOccurrencesOfString:@":" withString:@": "];如果他们用英语打字的话,这个方法效果很好。这就成了“我的朋友是:詹姆斯.”变成“我的朋友是:詹姆斯”这也没问题。
但我的问题是它在一段时间内也有一个空间。它会把"12:30“变成"12: 30”。我可以用所有的可能性来修改这些代码,这太过分了。
input = [input stringByReplacingOccurrencesOfString:@": 0" withString:@":0"];有什么更简单的方法来做这件事?我试过:
input = [input stringByReplacingOccurrencesOfString:@"\\b\\d\\d?:\\s\\d\\d\\b" withString:@"\\b\\d\\d?:\\d\\d\\b" options: NSRegularExpressionSearch range:NSMakeRange(0, [input length])];但是,所有这些都是从"hh: mm“更改为”bdd:ddb“,仅此而已。如何使NSString替换保留以前的字符?就像我怎样才能让它保持与以前相同的数字呢?我只想改变":“”成为":“在一个时间里”。
我尝试过使用NSNotFound的"if“语句,但它不起作用。我希望,如果它找到了"hh:mm“格式,不添加一个空格,但如果没有,则添加一个空格,但这不起作用。
发布于 2014-09-04 12:29:56
您对上一个版本的看法是正确的,但您需要使用NSRegularExpression。下面应该为您完成整个任务(在冒号后面添加空格,但当夹在两位数之间或后面已经有一个空格时):
NSString *input = @"My friends are:James, John. It's 10:30 right now.";
NSMutableString *workingString = [input mutableCopy];
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(((?<!(\\b\\d\\d)):)|(:(?!(\\d\\d\\b))))(?!\\s)" options:0 error:nil];
[regex replaceMatchesInString:workingString options:0 range:NSMakeRange(0, [workingString length]) withTemplate:@": "];
input = [workingString copy];
NSLog(@"%@", input); // Prints "My friends are: James, John. It's 10:30 right now."发布于 2014-09-03 07:23:10
你可以在这个way..If里做,你要么用字符串,要么只有没有数字的句子.
NSCharacterSet *s = [NSCharacterSet characterSetWithCharactersInString:@"1234567890"];
NSRange r = [input rangeOfCharacterFromSet:s];
if (r.location != NSNotFound)
{
input = [input stringByReplacingOccurrencesOfString:@":" withString:@": "];
}希望它能帮到你..。
https://stackoverflow.com/questions/25638352
复制相似问题