ios 查找字符串中某个字符的索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12385331/
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-08-30 20:03:36  来源:igfitidea点击:

Find the index of a character in a string

iphoneobjective-ciosnsstring

提问by fadd

I have a string NSString *Original=@"88) 12-sep-2012";or Original=@"8) blablabla";

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

I want to print only the characters before the ")" so how to find the index of the character ")". or how could i do it?

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

Thanks in advance.

提前致谢。

回答by Padavan

To print the characters before the first right paren, you can do this:

要在第一个右括号之前打印字符,您可以执行以下操作:

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

// If you need the character index:
NSUInteger index = str.length;

回答by Paresh Navadiya

U can find index of the character ")" like this:

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

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

回答by Vimal Venugopalan

You can use the following code to see the characters before ")"

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

   // 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]);

回答by freestyler

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

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

回答by Ravi Sharma

try the below code to get the index of a particular character in a string:-

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

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 )
}

and to get the string before the ) character use this:-

并在 ) 字符之前获取字符串,请使用:-

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

回答by Gloomcore

Another soluation:

另一个解决方案:

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);