How do I iterate through NSString on object c?

How do I iterate through an NSString object in an Objective c whiling maintaining an index for the character I am currently finding?

I want to increment the ASCII value of every third character by 3 and then print that incrementing character in a label in my UI.


source to share

2 answers

It's not clear if you just want to print the enlarged characters or everything. If the former, here's how you would do it:

NSString *myString = @"myString";
NSMutableString *newString = [NSMutableString string];
for (int i = 0; i < [myString length]; i++) 
    int ascii = [myString characterAtIndex:i];
    if (i % 3 == 0) 
        [newString appendFormat:@"%c",ascii];
myLabel.text = newString;




Will this do the trick?

NSString *incrementString(NSString *input)
    const char *inputUTF8 = [input UTF8String]; // notice we get the buffers so that we don't have to deal with the overhead of making many message calls.
    char *outputUTF8 = calloc(input.length + 1, sizeof(*outputUTF8));

    for (int i = 0; i < input.length; i++)
        outputUTF8[i] = i % 3 == 0 ? inputUTF8[i] + 3 : inputUTF8[i];

    NSString *ret = [NSString stringWithUTF8String:outputUTF8];
    free(outputUTF8); // remember to free the buffer when done!
    return ret;




All Articles