如何在NSString中添加百分號

我想在數字後加一個百分號。 大概是75%。 git

我該怎麼作? 我試過了: spa

[NSString stringWithFormat:@"%d\%", someDigit];

但這對我沒有用。 code


#1樓

若是在某些狀況下有幫助,則能夠使用unicode字符: orm

NSLog(@"Test percentage \uFF05");

#2樓

uese如下代碼。 unicode

NSString *searchText = @"Bhupi"
 NSString *formatedSearchText = [NSString stringWithFormat:@"%%%@%%",searchText];

將輸出: %Bhupi% 字符串


#3樓

彷佛若是%%後跟%@ ,則NSString將轉到一些奇怪的代碼,嘗試此操做,這對我有用 string

NSString *str = [NSString stringWithFormat:@"%@%@%@", @"%%", 
                 [textfield text], @"%%"];

#4樓

接受的答案不適用於UILocalNotification。 因爲某些緣由, %%%% (4個百分號)或Unicode字符' \% '僅對此有效。 it

回顧一下,格式化字符串時,能夠使用%% 。 可是,若是您的字符串是UILocalNotification的一部分,請使用%%%%\%io


#5樓

iOS 9.2.1,Xcode 7.2.1,啓用ARC form

您老是能夠本身附加'%',而無需在要附加的字符串中添加任何其餘格式說明符,就像這樣...

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]);

感謝全部原始貢獻者。 但願這能夠幫助。 乾杯!

相關文章
相關標籤/搜索