Sunday, May 12, 2013

NSString capitalizedString example ios


capitalizedString

Returns a capitalized representation of the receiver.
- (NSString *)capitalizedString
Return Value
A string with the first character from each word in the receiver changed to its corresponding uppercase value, and all remaining characters set to their corresponding lowercase values.
Discussion of [NSString capitalizedString]
A “word” here is any sequence of characters delimited by spaces, tabs, or line terminators (listed undergetLineStart:end:contentsEnd:forRange:). Other common word delimiters such as hyphens and other punctuation aren’t considered, so this method may not generally produce the desired results for multiword strings.
Case transformations aren’t guaranteed to be symmetrical or to produce strings of the same lengths as the originals. See lowercaseString for an example.
Example of [NSString capitalizedString]
 // original string
NSString *str = @"√ĀlgeBra";

// convert to a data object, using a lossy conversion to ASCII
NSData *asciiEncoded = [str dataUsingEncoding:NSASCIIStringEncoding
                         allowLossyConversion:YES];

// take the data object and recreate a string using the lossy conversion
NSString *other = [[NSString alloc] initWithData:asciiEncoded
                                        encoding:NSASCIIStringEncoding];
// relinquish ownership
[other autorelease];

// create final capitalized string
NSString *final = [other capitalizedString];
Example of [NSString capitalizedString]
NSString *firstCapChar = [[string substringToIndex:1] capitalizedString];
NSString *cappedString = [string stringByReplacingCharactersInRange:NSMakeRange(0,1) withString:firstCapChar];
Example of [NSString capitalizedString]
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]);