views:

64

answers:

4

Hi, everyone,

I want to ask a objective C question. I have a string retrieve from UITextField and I want to check the string contains the '@' or not. However, when I use the following code, it has some errors, can anyone help me? Thank you.

if([inputTextField.text rangeOfString:@"%"].location != NSNotFound)
    NSLog(@"It does not contain the %@");
else
    NSLog(@"It contains the %@");
A: 

In you NSLog statement you put a %@ but no arguments after.

Benj
@Benj, thank you for your reply. If I want to display the "@" in the statement, what should I do?
Questions
+2  A: 

Check the syntax:

if([inputTextField.text rangeOfString:myString].location == NSNotFound)
    NSLog(@"It does not contain the %@", myString);
else
    NSLog(@"It contains the %@", myString);

As you will see, the %@ will be replaced with the content of myString.

Sergei Lost
@Sergei Lost, thank you very much.
Questions
You are welcome.If you need to display the "@" then try doubling the symbol, i.e. use %@@ instead of %@. Not very sure if it will work, but you can try.
Sergei Lost
That code actually gives the wrong result. Change the "!=" comparrison to "==" to make it work correctly.
Claus Broch
You can put an @ sign in a string without escaping it e.g. `@"The string %@ contains an @"`. You do need to escape % though e.g. `@"The string %@ contains an %%"`
JeremyP
+1  A: 

You can use

NSLog([NSString stringWithUTF8String: "It does not contain the @"]);

or just

NSLog(@"It contains the @");

Note: Inside the @"..." construct, you should only use 7-bit ASCII symbols, see Apple's developer documentation.

swegi
+2  A: 

This code should do the trick:

if([inputTextField.text rangeOfString:@"@"].location == NSNotFound) 
    NSLog(@"It does not contain the @"); 
else 
    NSLog(@"It contains the @"); 
Claus Broch