Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate a random lowercase letter in Objective-C?

I'm new to the syntax, so that's where I need help. Conceptually, I get it. But syntax is foreign to me.

like image 919
Shamoon Avatar asked Dec 18 '25 17:12

Shamoon


2 Answers

Here's a succinct way to do it:

- (char)getRandomChar {
    return (char) (arc4random_uniform(26) + 'a');
}

This assumes you want 'a' to 'z', without any letters that have diacritical marks, such as å, ä, á, etc.

To return the character as an NSString:

- (NSString *)getRandomCharAsNString {
    return [NSString stringWithFormat:@"%c", arc4random_uniform(26) + 'a'];
}
like image 138
Steve McLeod Avatar answered Dec 21 '25 09:12

Steve McLeod


I would create a string "abcdefg..." and get a one character long substring at a random position.
Like this:

NSString *letters = @"abcdefghijklmnopqrstuvwxyz";
NSInteger index = arc4random_uniform([letters length]);
NSString *randomLetter = [letters substringWithRange:NSMakeRange(index, 1)];
like image 26
Matthias Bauch Avatar answered Dec 21 '25 09:12

Matthias Bauch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!