2012-03-07 4 views
4

NSString 메서드 [myString capitalizedString]을 사용하여 내 문자열의 모든 단어를 대문자로 사용합니다.capitalizedString은 숫자로 시작하는 단어를 올바르게 대문자로 표시하지 않습니다?

그러나 숫자로 시작하는 단어의 경우 대문자가 제대로 작동하지 않습니다.

i.e. 2nd chance 

n은 단어의 첫 글자없는 경우에도

2Nd Chance 

된다.

감사

+0

꽤 원액는 다음과 같습니다 http://www.pittle.org/weblog/how-to-capitalize-a-nsstring-instance-while-keeping-roman-numerals-all-capitalized_536 .html –

답변

5

당신은이 문제에 대한 자신의 솔루션을 출시 할 수 있습니다. Apple docs은 다중 단어 문자열과 특수 문자가있는 문자열에 대해 해당 기능을 사용하여 지정된 동작을 수행하지 못할 수도 있다고 설명합니다. 여기에이 도움이 될

NSString *text = @"2nd place is nothing"; 

// break the string into words by separating on spaces. 
NSArray *words = [text componentsSeparatedByString:@" "]; 

// create a new array to hold the capitalized versions. 
NSMutableArray *newWords = [[NSMutableArray alloc]init]; 

// we want to ignore words starting with numbers. 
// This class helps us to determine if a string is a number. 
NSNumberFormatter *num = [[NSNumberFormatter alloc]init]; 

for (NSString *item in words) { 
    NSString *word = item; 
    // if the first letter of the word is not a number (numberFromString returns nil) 
    if ([num numberFromString:[item substringWithRange:NSMakeRange(0, 1)]] == nil) { 
     word = [item capitalizedString]; // capitalize that word. 
    } 
    // if it is a number, don't change the word (this is implied). 
    [newWords addObject:word]; // add the word to the new list. 
} 

NSLog(@"%@", [newWords description]); 
+2

좋은 해결책. 나는 [[newWords valueForKey : @ "description"] componentsJoinedByString : @ ""]; '에 대해'[newWords description];'을 바꾸었지만, 전자는 괄호와 개행 문자를 포함하는 문자열을 반환하기 때문에. –

+0

내 문제가 해결되었습니다. – Hassy

0

불행하게도이 capitalizedString의 일반 작동 될 것으로 보인다.

아마도 좋지 않은 해결 방법/해킹은 변환 전에 각 숫자를 문자열로 바꾸고 나중에 다시 변경하는 것입니다.

그래서, "두번째 기회"-> "xyznd 기회"-> "Xyznd 기회"-> "두번째 기회"

+0

실제로 그것은 정말 좋은 해킹이 아니며, 다른 해결책이 있습니까? – aneuryzm

관련 문제