Answers:
您可以使用以下-hasPrefix:
方法NSString
:
目标C:
NSString* output = nil;
if([string hasPrefix:@"*"]) {
output = [string substringFromIndex:1];
}
迅速:
var output:String?
if string.hasPrefix("*") {
output = string.substringFromIndex(string.startIndex.advancedBy(1))
}
hasPrefix的效果特别好。例如,如果您要在中查找http网址NSString
,则可以使用componentsSeparatedByString
创建一个NSArray
,然后对数组进行迭代hasPrefix
以查找以http开头的元素。
NSArray *allStringsArray =
[myStringThatHasHttpUrls componentsSeparatedByString:@" "]
for (id myArrayElement in allStringsArray) {
NSString *theString = [myArrayElement description];
if ([theString hasPrefix:@"http"]) {
NSLog(@"The URL is %@", [myArrayElement description]);
}
}
hasPrefix
返回一个布尔值,该值指示给定的字符串是否与接收方的开头字符匹配。
- (BOOL)hasPrefix:(NSString *)aString,
参数aString
是您要查找的字符串。如果aString与接收方的起始字符匹配,则返回值为YES,否则为NO。如果aString
为空,则返回NO 。
使用characterAtIndex:
。如果第一个字符是星号,请使用substringFromIndex:
字符串“ *”代替。
另一种方法。
可以帮助某人...
if ([[temp substringToIndex:4] isEqualToString:@"http"]) {
//starts with http
}
作为更一般的答案,请尝试使用hasPrefix方法。例如,下面的代码检查字符串是否以10开头,这是用于标识特定问题的错误代码。
NSString* myString = @"10:Username taken";
if([myString hasPrefix:@"10"]) {
//display more elegant error message
}
我偶然发现了这段漂亮的代码,但我还没有在Stack上看到它的建议。仅当要删除或更改的字符存在时才起作用,这在许多情况下都很方便。如果字符不存在,则不会更改您的NSString:
NSString = [yourString stringByReplacingOccurrencesOfString:@"YOUR CHARACTERS YOU WANT TO REMOVE" withString:@"CAN either be EMPTY or WITH TEXT REPLACEMENT"];
这是我的用法:
//declare what to look for
NSString * suffixTorRemove = @"</p>";
NSString * prefixToRemove = @"<p>";
NSString * randomCharacter = @"</strong>";
NSString * moreRandom = @"<strong>";
NSString * makeAndSign = @"&amp;";
//I AM INSERTING A VALUE FROM A DATABASE AND HAVE ASSIGNED IT TO returnStr
returnStr = [returnStr stringByReplacingOccurrencesOfString:suffixTorRemove withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:prefixToRemove withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:randomCharacter withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:moreRandom withString:@""];
returnStr = [returnStr stringByReplacingOccurrencesOfString:makeAndSign withString:@"&"];
//check the output
NSLog(@"returnStr IS NOW: %@", returnStr);
这一行非常容易执行以下三个动作:
NSString* expectedString = nil;
if([givenString hasPrefix:@"*"])
{
expectedString = [givenString substringFromIndex:1];
}
hasPrefix:@"word"
您无需检查存储在中的多个值NSArray
?例如:NSArray *words = [NSArray arrayWithObjects:@"foo",@"bar",@"baz",nil];
?