1

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

String 1 Has:

Case Number
1
SKU Barcode


String 2 Has:

Case Number

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

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:

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


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

Thanks in advance!

  • 2
    Possible duplicate of [How do I check if a string contains another string in Objective-C?](http://stackoverflow.com/questions/2753956/how-do-i-check-if-a-string-contains-another-string-in-objective-c) – RajeshKumar R May 04 '17 at 05:09
  • @RajeshkumarR, I am using same only but why i am getting not matched result ..i am asking that only .Please help me – Chandrika Visvesh May 04 '17 at 05:14
  • Can you NSLog string1 and string2 and paste here? – RajeshKumar R May 04 '17 at 05:17
  • post ur strings data in ur question @ChandrikaVisvesh – NAVEEN KUMAR May 04 '17 at 05:21
  • Could you log `[string1 dataUsingEncoding:NSUTF8StringEncoding]` and the same for `string2`? There may be a invisible space between them or something like that. – Larme May 04 '17 at 12:22

3 Answers3

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.

RajeshKumar R
  • 13,989
  • 2
  • 35
  • 63
0

If you are supporting iOS 8.0 onwards, you can use 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).

norders
  • 1,051
  • 7
  • 10
0

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

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