Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 690
BIGGIe Avatar asked Dec 11 '25 11:12

BIGGIe


2 Answers

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);
like image 112
ateich Avatar answered Dec 14 '25 01:12

ateich


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];
like image 22
Midhun MP Avatar answered Dec 14 '25 01:12

Midhun MP



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!