查找字符串中字符的索引

时间:2012-09-12 09:41:22

标签: iphone objective-c ios nsstring

我有一个字符串NSString *Original=@"88) 12-sep-2012";Original=@"8) blablabla";

我想只打印“)”之前的字符,以便如何找到字符“)”的索引。或者我怎么能这样做?

提前致谢。

6 个答案:

答案 0 :(得分:14)

NSString *str = [[yourString componentsSeparatedByString:@")"] objectAtIndex:0];

答案 1 :(得分:8)

U可以找到字符“)”的索引,如下所示:

NSString *Original=@"88) 12-sep-2012";
NSRange range = [Original rangeOfString:@")"];
if(range.location != NSNotFound)
{
 NSString *result = [Original substringWithRange:NSMakeRange(0, range.location)];
}

答案 2 :(得分:4)

您可以使用以下代码查看“)”

之前的字符
   // this would split the string into values which would be stored in an array
   NSArray *splitStringArray = [yourString componentsSeparatedByString:@")"];
   // this would display the characters before the character ")"
   NSLog(@"%@", [splitStringArray objectAtIndex:0]);

答案 3 :(得分:3)

NSUInteger index = [Original rangeOfString:@")"];

NSString *result = [Original substringWithRange:NSMakeRange(0, index)];

答案 4 :(得分:3)

尝试以下代码来获取字符串中特定字符的索引: -

NSString *string = @"88) 12-sep-2012";
NSCharacterSet *charSet = [NSCharacterSet characterSetWithCharactersInString:@")"];
NSRange range = [string rangeOfCharacterFromSet:charSet];

if (range.location == NSNotFound) 
{
    // ... oops
}
else {
    NSLog(@"---%d", range.location);
    // range.location is the index of character )
}

并获取字符串之前的字符串使用: -

NSString *str = [[string componentsSeparatedByString:@")"] objectAtIndex:0];

答案 5 :(得分:1)

另一个解决方案:

NSString *Original=@"88) 12-sep-2012";
NSRange range = [Original rangeOfString:@")"];
NSString *result = Original;

if (range.location != NSNotFound)
{
    result = [Original substringToIndex:range.location];
}

NSLog(@"Result: %@", result);