12

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

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

提前致谢。

4

6 回答 6

16

要打印第一个右括号之前的字符,您可以这样做:

NSString *str = [[yourString componentsSeparatedByString:@")"] objectAtIndex:0];
NSLog(@"%@", str);

// If you need the character index:
NSUInteger index = str.length;
于 2012-09-12T09:45:18.393 回答
10

你可以像这样找到字符“)”的索引:

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

您可以使用以下代码查看“)”之前的字符

   // 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]);
于 2012-09-12T09:44:29.970 回答
3
NSUInteger index = [Original rangeOfString:@")"];

NSString *result = [Original substringWithRange:NSMakeRange(0, index)];
于 2012-09-12T09:47:17.707 回答
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];
于 2012-09-12T10:32:01.280 回答
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);
于 2012-09-12T09:49:39.350 回答