K.P.
K.P.

Reputation: 324

How to split the text of a UITextField into individual characters

I have a UITextField and suppose there are 5 characters in this textbox for e.g. hello.

Now I want to divide this word into single character i.e. 'h','e','l','l','o';

then how can I perform this kind of action.

Any help will be appreciated.

Upvotes: 0

Views: 710

Answers (3)

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

I think using the for loop is a good idea, but to get exactly what you asked for, use -getCharacters:range:. Here is an example:

- (void)testGetCharsInRange
{
    NSString *text = @"This is a test string, will it work?";

    unichar *chars = calloc([text length], sizeof(unichar));
    [text getCharacters:chars range:NSMakeRange(0, [text length])];

    STAssertEquals(chars[[text length] - 1], (unichar)'?', nil);

    free(chars);
}

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122391

First get the string value from the textfield:

NSString *text = myTextField.text;

Then you can iterate each character:

NSUInteger len = [text length];
for (NSUInteger i = 0; i < len; i++)
{
    unichar c = [text characterAtIndex:i];
    // Do something with 'c'
}

Upvotes: 1

JordanMazurke
JordanMazurke

Reputation: 1123

Just use the NSString method UTF8String

const char *str = [textField.text UTF8String];

You then have an array of UTF8 chars

NOTE: ensure you are happy with the UTF8 encoding i.e. no non standard characters

Upvotes: 0

Related Questions