[objective-c] NSString에 퍼센트 부호를 추가하는 방법

숫자 뒤에 문자열에 백분율 기호를 넣고 싶습니다. 이와 같은 것 : 75 %.

어떻게해야합니까? 나는 시도했다 :

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

그러나 그것은 나를 위해 작동하지 않았습니다.



답변

퍼센트 기호 NSString형식 의 코드 는 %%입니다. 이것은 또한 마찬가지입니다 NSLog()printf()형식을 지원합니다.


답변

퍼센트 부호의 이스케이프 코드는 “%%”이므로 코드는 다음과 같습니다.

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

또한 다른 모든 형식 지정자는 개념적 문자열 기사 에서 찾을 수 있습니다.


답변

어떤 경우에는 도움이된다면 유니 코드 문자를 사용할 수 있습니다.

NSLog(@"Test percentage \uFF05");


답변

UILocalNotification에 허용되는 답변이 작동하지 않습니다. 어떤 이유로 %%%%(4 퍼센트 부호) 또는 유니 코드 문자 ‘ \uFF05‘만이 작업을 수행합니다.

요약하면 문자열을 형식화 할 때 사용할 수 있습니다 %%. 그러나 문자열이 UILocalNotification의 일부인 경우 %%%%또는을 사용하십시오 \uFF05.


답변

경우 것 같다 %%로모그래퍼 다음 %@은이 NSString이상한 코드로 이동합니다 이것을 시도하고이 나를 위해 일

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


답변

uese 다음 코드.

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

모든 원래 기여자에게 감사합니다. 도움이 되었기를 바랍니다. 건배!