如何在Objective-c中的字符串中查找子字符串

时间:2020-11-28 19:21:09

I want to find a word in a string i.e,whether a word is present in particular string or not.

我想在一个字符串中找到一个单词,即一个单词是否存在于特定的字符串中。

String 1 Has:

字符串1有:

Case Number
1
SKU Barcode

案例编号1 SKU条形码


String 2 Has:

字符串2有:

Case Number

案件编号

I want to find whether Case Number is present in string 1 or not .

我想查找字符串1中是否存在案例编号。

if ([string1 rangeOfString:string2].location !=NSNotFound) {

        NSLog(@"matched");} 
else 
{ NSLog(@"not matched");}

but here i am getting not matched ...why ..And then what is the difference of using .location and .length Output:

但在这里我得不到匹配...为什么..然后使用.location和.length输出的区别是什么:

2017-05-04 11:38:33.128495 Link[26540:17390387] String 1: Case Number
1
SKU Barcode

2017-05-04 11:38:33.128495链接[26540:17390387]字符串1:案例编号1 SKU条形码


2017-05-04 11:38:33.129301 Link[26540:17390387] String 2: Case Number

2017-05-04 11:38:33.129301链接[26540:17390387]字符串2:案例编号

Thanks in advance!

提前致谢!

3 个解决方案

#1


1  

NSString *string1 = @"Case Number \n 1 \n SKU Barcode";
NSString *string2 = @"Case Number";
if ([string1 rangeOfString:string2].location !=NSNotFound) {

    NSLog(@"matched");}
else
{ NSLog(@"not matched");}

}

It works for me.

这个对我有用。

#2


0  

If you are supporting iOS 8.0 onwards, you can use containsString:

如果您支持iOS 8.0以上,则可以使用containsString:

if ([string1 containsString:string2])
    NSLog(@"matched");
else
    NSLog(@"not matched");

If this doesn't work, then there's something wrong with one or both of your strings (e.g. additional space or control characters at the end).

如果这不起作用,那么你的一个或两个字符串就会出现问题(例如最后的附加空格或控制字符)。

#3


0  

Your string2 contains characters other than @"Case Number". Test by inserting the following lines into your code.

您的string2包含@“案例编号”以外的字符。通过在代码中插入以下行进行测试。

if([string2 isEqualToString:@"Case Number"]) NSLog(@"String 2 is OK");
else NSLog(@"String 2 is bad!");

#1


1  

NSString *string1 = @"Case Number \n 1 \n SKU Barcode";
NSString *string2 = @"Case Number";
if ([string1 rangeOfString:string2].location !=NSNotFound) {

    NSLog(@"matched");}
else
{ NSLog(@"not matched");}

}

It works for me.

这个对我有用。

#2


0  

If you are supporting iOS 8.0 onwards, you can use containsString:

如果您支持iOS 8.0以上,则可以使用containsString:

if ([string1 containsString:string2])
    NSLog(@"matched");
else
    NSLog(@"not matched");

If this doesn't work, then there's something wrong with one or both of your strings (e.g. additional space or control characters at the end).

如果这不起作用,那么你的一个或两个字符串就会出现问题(例如最后的附加空格或控制字符)。

#3


0  

Your string2 contains characters other than @"Case Number". Test by inserting the following lines into your code.

您的string2包含@“案例编号”以外的字符。通过在代码中插入以下行进行测试。

if([string2 isEqualToString:@"Case Number"]) NSLog(@"String 2 is OK");
else NSLog(@"String 2 is bad!");