3

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?

BIGGIe
  • 41
  • 4
  • You are casting to `NSString` first then reading the user input. `NSString *otherWord = [NSString stringWithFormat:@"%s", word]; scanf("%s", word);` – Midhun MP Jan 17 '15 at 05:03

2 Answers2

1

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);
ateich
  • 520
  • 3
  • 10
  • It makes no sense to fill the `word` array/string before then calling `scanf()`, which replaces the content. (Setting aside the fact that `scanf()` to input a string without specifying a maximum field width is horribly unsafe because it can overrun the provided buffer.) – Ken Thomases Jan 17 '15 at 05:52
1

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];
Midhun MP
  • 103,496
  • 31
  • 153
  • 200