简体   繁体   中英

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?

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);

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM