Tushar Chutani
Tushar Chutani

Reputation: 1560

NSString/NSMutableString strange behaviour

OK here is nsmutablestring

data = [NSMutableString stringWithFormat:@"&cb_games%5B%5D="];

Now when ever I try to print or use this string I get big number instead of %5B and %5D not sure why this is happeing any help would be apritiated

thanks

Upvotes: 1

Views: 172

Answers (5)

Mat
Mat

Reputation: 7633

Try this:

NSString * data = [NSMutableString stringWithFormat:@"&cb_games%%5B%%5D="];
NSLog(@"%@",data);

Upvotes: 2

EmptyStack
EmptyStack

Reputation: 51374

The reason you get unexpected output is that '%' is used as conversion specifier in printf and obviously NSLog and NSString formattings. You need to escape '%' if you don't want it to be interpreted as a conversion specifier. You can escape '%' by preceding it with another '%' like '%%'.

Your string should look like,

@"&cb_games%%5B%%5D="

And the @August Lilleaas's answer is also noteworthy.

Upvotes: 4

Daniel Broad
Daniel Broad

Reputation: 2522

Did you mean to write?

data = [NSMutableString stringWithString@"&cb_games%5B%5D="]

Upvotes: 0

August Lilleaas
August Lilleaas

Reputation: 54593

stringWithFormat is basically printf, and it attempts to replace your percentages with values that you haven't provided, which is why wierd stuff happens.

[NSMutableString stringWithFormat:@"Hello: %d", 123];
// @"Hello: 123"

If you want a mutable string from a string, try this:

[NSMutableString stringWithString:@"Abc %2 %3"];
// @"Abc %2 %3"

Upvotes: 2

Simon
Simon

Reputation: 9021

The % is used for string formatting and stuff. I imagine you need to escape the character or something, possibly with a slash.

Upvotes: 0

Related Questions