how to get first three characters of an NSString?

后端 未结 3 546
旧巷少年郎
旧巷少年郎 2020-12-07 19:57

How can I return the first three characters of an NSString?

相关标签:
3条回答
  • 2020-12-07 20:08
     mystr=[mystr substringToIndex:3];
    

    Be sure your string has atleast 3 ch.. o.e. it will crash the app.

    Here are some other links to check NSsting operations...

    Link1

    Link2

    Apple Link

    0 讨论(0)
  • 2020-12-07 20:24

    First, you have to make sure that the string contains at least 3 characters:

    NSString *fullString = /* obtain from somewhere */;
    NSString *prefix = nil;
    
    if ([fullString length] >= 3)
        prefix = [fullString substringToIndex:3];
    else
        prefix = fullString;
    

    substringToIndex: will throw an exception if the index you provide is beyond the end of the string.

    0 讨论(0)
  • 2020-12-07 20:25

    the right way is:

    text = [text substringToIndex:NSMaxRange([text rangeOfComposedCharacterSequenceAtIndex:2])];
    

    substringToIndex of NSString is indexing by code unit, emoji takes two code units.

    make sure check the index yourself.

    0 讨论(0)
提交回复
热议问题