iPhone Development

Just another iPhone Blog

Autocapitalizing string

This code snippet requires RegexLite Library.Check here

#import “RegexKitLite.h”

@interface NSString(RegExAdditons)

 

+(NSString*)autocapitalizedStringForString:(NSString*)inString;

 

@end

 

 

@implementation NSString(RegExAdditons)

 

+(NSString*)autocapitalizedStringForString:(NSString*)inString

{

NSMutableString *completedString =[NSMutableString stringWithString:@””];

if( inString && ![inString isEqualToString:@””])

{

 

/* Regular Expression for extracting the words in a sentence*/

NSString   *regexString  = @”(\\w*)”;

completedString =[NSMutableString stringWithString:inString];

 

NSUInteger totalLength = [completedString length];

NSUInteger currentIndex=0;

 

/* With the help of RegexLite, we extract all the words in the given string*/

NSArray * components = [inString componentsMatchedByRegex:regexString];

int index =0, count = [components count];

 

for( ; index < count;index++) {

 

NSString *matchedString = [components objectAtIndex:index];

 

NSUInteger matchedStringLength = [matchedString length];

if( matchedStringLength>0) {

unichar character=;

[matchedString getCharacters:&character range:NSMakeRange(0, 1)];

 

/* if the first character of the word is a ASCII character, then change the letter to its Upper Case version*/

if( isascii(character) ) {

 

/*Find the Location of the First letter of the matchedString within the given string*/

NSRange range = [completedString rangeOfString:matchedString options:NSLiteralSearch range:NSMakeRange(currentIndex, totalLength-currentIndex)];

 

if( range.location != NSNotFound) {

 

/*replace the first letter of the matched string to its upper case version*/

[completedString replaceCharactersInRange:NSMakeRange(range.location, 1) withString:[NSString stringWithFormat:@”%c”, toupper(character)]];


currentIndex+=matchedStringLength;

}

}

}

}

}

return completedString;

}

@end


 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: