How to capture last 4 characters from NSString

你。 提交于 2019-11-28 18:12:36

Use the substringFromIndex method,

OBJ-C:

NSString *trimmedString=[string substringFromIndex:MAX((int)[string length]-4, 0)]; //in case string is less than 4 characters long.

SWIFT:

let trimmedString: String = (s as NSString).substringFromIndex(max(s.length-4,0))

Try This,

NSString *lastFourChar = [yourNewString substringFromIndex:[yourNewString length] - 4];

The Swift answer provided by KingOfBliss is producing an error for me as of XCode 7.3, and should not be used going forward due to bridging to NS classes, which should be removed in Swift 3.0.

A better example that considers an invalid range, as well as the possibility of special characters to provide the right spot to remove:

The string in question: Voulez-vous un café?

var trimmedString = "Voulez-vous un caf\u{65}\u{301}?"

let stringSize = trimmedString.characters.count
let startIndex = 4

if stringSize >= startIndex {
    let range = trimmedString.endIndex.advancedBy(-startIndex)..<trimmedString.endIndex
    trimmedString.removeRange(range)
}

This will produce an answer of Voulez-vous un c.

By accessing the string with the start & end index values, you protect against situations where not all chars are the same size (ex: \u{65}\u{301})

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!