Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS

Rashii Henry
Rashii Henry
16,433 Points

Returning Integers in a string?

why does the following code print out the numbers 49 - 54 in ascending order?

where is the console retrieving these values?

- (void)viewDidLoad
{
    [super viewDidLoad];

    _nString = [NSString stringWithFormat:@"123456"];

    for (int i = 0; i < _nString.length; i++)
    {
        NSLog(@"%i",[_nString characterAtIndex:i]);
    }
}
Michael Owens
Michael Owens
5,591 Points

It is returning the characters from your string "123456" in ASCII value

In other words:

49 = '1'

50 = '2'

51 = '3'

.

.

.

For a look at the ASCII table look here: http://www.asciitable.com/

2 Answers

Don Miller
Don Miller
1,773 Points

You may want to cast it as an integer or make it an integer. Otherwise, Michael is correct that the value of @"1" is a unicode value, not the number 1.

- (void)viewDidLoad
{
    [super viewDidLoad];

    _nString = [NSString stringWithFormat:@"123456"];

    for (int i = 0; i < (int)_nString.length; i++)
    {
        NSLog(@"%i",[_nString characterAtIndex:i]);
    }
}
Rashii Henry
Rashii Henry
16,433 Points

Thanks to you both.

I just want to be able to return the lowest number in any given string.

Im not sure if I'm taking the right approach. I was going to use containsString.

I've casted the length in the for loop to an int like you did above and I'm still receiving ASCII characters in the console.

I also tried adding intValue at the end of the declaration. but implicit conversions aren't allowed with ARC.

Michael Owens
Michael Owens
5,591 Points

By lowest number, I'm assuming lowest single digit number. First your for loop isn't parsing the string correctly. There are many ways to do this.

Second you may have to typecast the output as well.

NSLog(@"%i",[(int)_nString characterAtIndex:i]);

hope that helps