开发者

Percentage with NSString

开发者 https://www.devze.com 2023-02-18 03:27 出处:网络
I have an input NSString and I want to get ouput with % at the end I tried to do the following but it failed

I have an input NSString and I want to get ouput with % at the end

I tried to do the following but it failed

NSLog([NSString stringWithFormat:@"%@%%", self.tName.text ] ); 

where tName is UITextfield

the problem is at console if i typed A the output will be A not A%

Any suggestion to 开发者_StackOverflow社区solve that?


You're not using NSLog() correctly. NSLog() is meant to be called with a constant format string (%@%%, for instance), and be passed in arguments. What you're doing is parsing these arguments beforehand, and then passing the string you want to print to NSLog(), which doesn't work.

When you write [NSString stringWithFormat:@"%@%%", @"Hello!"], the string you get back is @"Hello!%", which is what you want to print. However, when you pass it into NSLog(), it thinks that that is the format string it needs to parse, sees the single percent sign and doesn't know what to do (it expects getting something after the percent sign), so it ignores it. Essentially, what you're doing is this:

NSLog(@"Hello!%");

Try it out and you'll see it won't work. Using a correct NSLog() call will fix your problem:

NSLog(@"%@%%", self.tName.text);

Read up on NSLog() and its variable counterpart, NSLogv() here.


I'm not sure what your problem is, but simply using %% will output the percentage sign, as per the String Format Specifiers section of the String Programming Guide.


I just have tested your case like the following:

NSString *s = @"100";
NSLog(@"%@%%",s);

the Output was: 100%

try this would it make a difference?

 NSLog(@"%@%%",self.tName.text);
0

精彩评论

暂无评论...
验证码 换一张
取 消