我正在嘗試通過Hashtag
創建搜索。用戶可以輸入一個單詞。如何過濾用戶輸入,以便每個單詞都有一個前綴
現在我需要驗證:
用戶具有每字
只有1#標籤有每個字只有1#標籤。
如果這個詞不是以hashtag開頭,那麼放置一個。
用戶未inputed超過1個空間刪除多餘的空間
用戶沒有使用其他常用定界符來separe像昏迷或半昏迷
我生產的話下面的代碼,但每次我開始一個新的單詞,它會刪除這兩個單詞之間的空間,它變得不可能有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;
}