我有一个字符串NSString *Original=@"88) 12-sep-2012";
或Original=@"8) blablabla";
我只想打印“)”之前的字符,所以如何找到字符“)”的索引。或者我该怎么做?
提前致谢。
我有一个字符串NSString *Original=@"88) 12-sep-2012";
或Original=@"8) blablabla";
我只想打印“)”之前的字符,所以如何找到字符“)”的索引。或者我该怎么做?
提前致谢。
要打印第一个右括号之前的字符,您可以这样做:
NSString *str = [[yourString componentsSeparatedByString:@")"] objectAtIndex:0];
NSLog(@"%@", str);
// If you need the character index:
NSUInteger index = str.length;
你可以像这样找到字符“)”的索引:
NSString *Original=@"88) 12-sep-2012";
NSRange range = [Original rangeOfString:@")"];
if(range.location != NSNotFound)
{
NSString *result = [Original substringWithRange:NSMakeRange(0, range.location)];
}
您可以使用以下代码查看“)”之前的字符
// 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]);
NSUInteger index = [Original rangeOfString:@")"];
NSString *result = [Original substringWithRange:NSMakeRange(0, index)];
尝试以下代码以获取字符串中特定字符的索引:-
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];
另一个解决方案:
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);