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!

5
  • 2
    Possible duplicate of How do I check if a string contains another string in Objective-C? Commented May 4, 2017 at 5:09
  • @RajeshkumarR, I am using same only but why i am getting not matched result ..i am asking that only .Please help me Commented May 4, 2017 at 5:14
  • Can you NSLog string1 and string2 and paste here? Commented May 4, 2017 at 5:17
  • post ur strings data in ur question @ChandrikaVisvesh Commented May 4, 2017 at 5:21
  • Could you log [string1 dataUsingEncoding:NSUTF8StringEncoding] and the same for string2? There may be a invisible space between them or something like that. Commented May 4, 2017 at 12:22

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

5 Comments

,String one 1 has three lines ,case number is in 1st line ,1 in 2nd line , SKU Barcode in 3 rd line
Can you show how you've created string1 and string2?
It is coming from server , i have not created this string
@ChandrikaVisvesh Can you NSLog string1 and string2 and paste here?
1

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.