BIGGIe
BIGGIe

Reputation: 41

substringWithRange works with hard coded string, but not user-input string

When I hard code the string in question and attempt to substringWithRange, it works just fine. But when I take a user input as a char and cast it to NSString, it throws up an NSRange exception. Is it because I am casting a char?

This doesn't work:

    char word[30];
    NSString *otherWord = [NSString stringWithFormat:@"%s", word];
    scanf("%s", word);
    NSString *firstCharacter = [otherWord substringWithRange:NSMakeRange(0, 3)];

However, this one does:

    char word[30];
    NSString *otherWord = @"SomeString";
    scanf("%s", word);
    NSString *firstCharacter = [otherWord substringWithRange:NSMakeRange(0, 3)];

I also checked to make sure that "otherWord" has the proper value, which it does.

Any suggestions?

Upvotes: 3

Views: 97

Answers (2)

Midhun MP
Midhun MP

Reputation: 107231

In your code, you are creating the string first using the character array. After that you are reading the user input:

Change :

NSString *otherWord = [NSString stringWithFormat:@"%s", word];
scanf("%s", word);

to:

scanf("%s", word);
NSString *otherWord = [NSString stringWithCString:word encoding:NSUTF8StringEncoding];

Upvotes: 1

ateich
ateich

Reputation: 520

You need to set the char word[30] equal to something, otherwise it will not have enough characters in it when converted to run subStringWithRange on it. Hence the NSRange exception.

char word[30] = {'a', 'b', 'c', 'd'};
scanf("%s", word);
NSString *otherWord = [NSString stringWithCString:word encoding:NSASCIIStringEncoding];
NSString *firstCharacter = [otherWord substringWithRange:NSMakeRange(0, 3)];
NSLog(@"%@",firstCharacter);

Upvotes: 1

Related Questions