xcode 目标 C:检查字符串的开头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5662031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 20:49:31  来源:igfitidea点击:

OBjective C: check the beginning of a string

objective-cxcodensstring

提问by cyclingIsBetter

I must verify the beginning of a string: my example string is

我必须验证字符串的开头:我的示例字符串是

NSString *string1 = @"Hello World";

then I must do an if, example:

那么我必须做一个 if,例如:

 if (string1 startwith "Hello")

How can I do this in objective c?

我怎样才能在目标 c 中做到这一点?

回答by Jim Blackler

if ([string1 hasPrefix:@"Hello"])

回答by NSResponder

Read the documentation for the NSString class. You'll find all kinds of surprises.

阅读 NSString 类的文档。你会发现各种各样的惊喜。

回答by Mick Walker

How about doing it this way:

这样做怎么样:

NSRange aRange = [myString rangeOfString:@"Hello"];
if (aRange.location ==NSNotFound) {
  NSLog(@"string not found");
} else {
  NSLog(@"string was at index %d ",aRange.location);
}

Based on the range, you can determine where in the string the item occurs

根据范围,您可以确定项目出现在字符串中的哪个位置