How to remove the last unicode symbol from NSString

前端 未结 3 1071
终归单人心
终归单人心 2020-12-15 13:31

I have implemented a custom keyboard associated with a text field, so when the user presses the delete button, I remove the last character from the string, and manually upda

相关标签:
3条回答
  • 2020-12-15 14:04

    If you can't get this to work by default, then use an if/else block and test if the last character is part of a special character. If it is, use the substring to length-2, otherwise use the substring to length-1.

    0 讨论(0)
  • 2020-12-15 14:05

    I don't know exactly what the problem is there with the special characters byte length.

    What i suggest is:

    • Store string length to a param, before adding any new characters
    • If user selects backspace (remove last characters) then remove the string from last length to new length. Means for example last saved string length is 5 and new string length is 7 then remove get a new string with the index from 0 to 4, so it will crop the remaining characters.

    This is the other way around to do as i don't know the exact what problem internally.

    But i guess logically this solution should work.

    Enjoy Coding :)

    0 讨论(0)
  • 2020-12-15 14:07

    Here's the problem. NSStrings are encoded using UTF-16. Many common Unicode glyphs take up only one unichar (a 16 bit unsigned value). However, some glyphs take up two unichars. Even worse, some glyphs can be composed or decomposed, e.g.é might be one Unicode code point or it might be two - an acute accent followed by an e. This makes it quite difficult to do what you want viz delete one "character" because it is really hard to tell how many unichars it takes up.

    Fortunately, NSString has a method that helps with this: -rangeOfComposedCharacterSequenceAtIndex:. What you need to do is get the index of the last unichar, run this method on it, and the returned NSRange will tell you where to delete from. It goes something like this (not tested):

    NSUInteger lastCharIndex = [myString length] - 1; // I assume string is not empty
    NSRange rangeOfLastChar = [myString rangeOfComposedCharacterSequenceAtIndex: lastCharIndex];
    myNewString = [myString substringToIndex: rangeOfLastChar.location];
    
    0 讨论(0)
提交回复
热议问题