我正在尝试通过创建搜索Hashtag
。用户可以输入单词。
现在我需要验证:
用户每个单词只有 1 个标签
每个单词只有 1 个标签。
如果单词不以标签开头,则放置一个。
用户输入的空格不超过 1 个 删除多余的空格
用户没有使用其他常见的分隔符来分隔 coma 或 semi-coma 等单词
我已经生成了以下代码,但是每次我开始一个新单词时,它都会删除两个单词之间的空格,并且不可能有 2 个单词,或者它只允许我有第二个单词但它不会添加#
到第二个字。
任何人都可以帮我验证我的验证逻辑吗?
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
// Delete double spaces between words
NSString* str = [textField.text stringByReplacingOccurrencesOfString:@" " withString:@" "];
if ( [str isEqualToString:@""] ) {
return YES;
}
// Check for other methods that people could use to separate strings
str = [str stringByReplacingOccurrencesOfString:@"," withString:@"#"];
str = [str stringByReplacingOccurrencesOfString:@";" withString:@"#"];
// separate string by Hashtag
NSArray * words = [str componentsSeparatedByString:@"#"];
NSMutableArray * ma =[[NSMutableArray alloc]init];
for (NSString* str4 in words) {
if ( ![str4 isEqualToString:@""]) {
// Separate string by space
NSArray * words2 = [str4 componentsSeparatedByString:@" "];
if ( [words2 count] != 0) {
[ma addObjectsFromArray:words2];
}
}
}
words = [[NSArray alloc]initWithArray:ma];
NSString * newStr = [[NSString alloc]init];
// Make the new string
for (NSString* str2 in words) {
if ( ![str2 isEqualToString:@""]) {
NSString* str3 = str2;
str3 = [NSString stringWithFormat:@"#%@ ",str3];
newStr = [newStr stringByAppendingString:str3];
}
}
textField.text = newStr;
return YES;
}