【发布时间】:2010-10-18 21:19:46
【问题描述】:
我想在我的字符串中的一个数字后面加上一个百分号。像这样:75%。
我怎样才能做到这一点?我试过了:
[NSString stringWithFormat:@"%d\%", someDigit];
但这对我不起作用。
【问题讨论】:
标签: objective-c nsstring string-literals
我想在我的字符串中的一个数字后面加上一个百分号。像这样:75%。
我怎样才能做到这一点?我试过了:
[NSString stringWithFormat:@"%d\%", someDigit];
但这对我不起作用。
【问题讨论】:
标签: objective-c nsstring string-literals
NSString 格式的百分号代码是%%。 NSLog() 和 printf() 格式也是如此。
【讨论】:
NSLog 将其第一个参数视为格式字符串,但您已经使用stringWithFormat: 格式化了该字符串。只需说NSLog(@"%@%%", self.Ptextfield.text)。
百分号的转义码是“%%”,所以你的代码应该是这样的
[NSString stringWithFormat:@"%d%%", someDigit];
此外,所有其他格式说明符都可以在 Conceptual Strings Articles 找到
【讨论】:
如果在某些情况下有帮助,可以使用 unicode 字符:
NSLog(@"Test percentage \uFF05");
【讨论】:
\uFF05 当它是UILocalNotification 中的NSString 的一部分时对我有用,而不是%%。谢谢!
接受的答案不适用于 UILocalNotification。出于某种原因,%%%%(4 个百分号)或 unicode 字符“\uFF05”仅适用于此。
回顾一下,格式化字符串时,您可以使用%%。但是,如果您的字符串是 UILocalNotification 的一部分,请使用 %%%% 或 \uFF05。
【讨论】:
如果%% 后跟%@,NSString 似乎会出现一些奇怪的代码
试试这个,这对我有用
NSString *str = [NSString stringWithFormat:@"%@%@%@", @"%%",
[textfield text], @"%%"];
【讨论】:
使用以下代码。
NSString *searchText = @"Bhupi"
NSString *formatedSearchText = [NSString stringWithFormat:@"%%%@%%",searchText];
将输出:%Bhupi%
【讨论】:
iOS 9.2.1,Xcode 7.2.1,启用 ARC
您始终可以在附加的字符串中单独附加 '%' 而无需任何其他格式说明符,就像这样...
int test = 10;
NSString *stringTest = [NSString stringWithFormat:@"%d", test];
stringTest = [stringTest stringByAppendingString:@"%"];
NSLog(@"%@", stringTest);
适用于 iOS7.0+
要将答案扩展到可能导致您发生冲突的其他字符,您可以选择使用:
- (NSString *)stringByAddingPercentEncodingWithAllowedCharacters:(NSCharacterSet *)allowedCharacters
一步一步写出来是这样的:
int test = 10;
NSString *stringTest = [NSString stringWithFormat:@"%d", test];
stringTest = [[stringTest stringByAppendingString:@"%"]
stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]];
stringTest = [stringTest stringByRemovingPercentEncoding];
NSLog(@"percent value of test: %@", stringTest);
或简写:
NSLog(@"percent value of test: %@", [[[[NSString stringWithFormat:@"%d", test]
stringByAppendingString:@"%"] stringByAddingPercentEncodingWithAllowedCharacters:
[NSCharacterSet alphanumericCharacterSet]] stringByRemovingPercentEncoding]);
感谢所有原始贡献者。希望这可以帮助。干杯!
【讨论】: