mercredi 7 septembre 2016

Uppercase random characters in a NSString

I'm trying to figure out the best approach to a problem. I have an essentially random alphanumeric string that I'm generating on the fly:

NSString *string = @"e04325ca24cf20ac6bd6ebf73c376b20ac57192dad83b22602264e92dac076611b51142ae12d2d92022eb2c77f";

You can see that there are no special characters, just numbers and letters, and all the letters are lowercase. Changing all the letters in this string to uppercase is easy:

[string capitalizedString];

The hard part is that I want to capitalize random characters in this string, not all of them. For example, this could be the output on one execution:

E04325cA24CF20ac6bD6eBF73C376b20Ac57192DAD83b22602264e92daC076611b51142AE12D2D92022Eb2C77F

This could be the output on another, since it's random:

e04325ca24cf20aC6bd6eBF73C376B20Ac57192DAd83b22602264E92dAC076611B51142AE12D2d92022EB2c77f

In case it makes this easier, let's say I have two variables as well:

int charsToUppercase = 12;//hardcoded value for how many characters to uppercase here
int totalChars = 90;//total string length

In this instance it would mean that 12 random characters out of the 90 in this string would be uppercased. What I've figured out so far is that I can loop through each char in the string relatively easily:

NSUInteger len = [string length];
unichar buffer[len+1];

[string getCharacters:buffer range:NSMakeRange(0, len)];

NSLog(@"loop through each char");
for(int i = 0; i < len; i++) {
    NSLog(@"%C", buffer[i]);
}

Still stuck with selecting random chars in this loop to uppercase, so not all are uppercased. I'm guessing a condition in the for loop could do the trick well, given that it's random enough.




Aucun commentaire:

Enregistrer un commentaire