DennisW83
DennisW83

Reputation: 111

xcode cut last characters from string

I am working on a Xcode program and need to cut the last 5 characters from a string.

Does anybody know how to cut the last 5 characters from a NSString?

Upvotes: 11

Views: 20228

Answers (2)

Heider Sati
Heider Sati

Reputation: 2614

I hope it's not too late for this answer:

NSString *str = @"1234567890";
NSString *newStr;

newStr = [str substringWithRange:NSMakeRange(str.length -1, 1)];

NSLog(@"%@", newStr);

Although you provided a string of "1234567889" and the above code should work fine, however, in real life if it's a different string then please check to ensure that it's not empty before doing the above, otherwise, str.length would return -1 causing an error.

I hope this helps.

Kind Regards, Heider Sati

Upvotes: 1

Philip Kramer
Philip Kramer

Reputation: 302

just looked for it my self few minutes ago

NSString *str = @"1234567890";
NSString *newStr;

newStr = [str substringToIndex:[str length]-5];

NSLog(@"%@", newStr);

Upvotes: 28

Related Questions