Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove first 3 characters from NSString?

I have a string like this "A. rahul VyAs"

and i want to remove "A. " and the space after the "A." so that new string would be "rahul VyAs"

How do i achieve this?

like image 268
Rahul Vyas Avatar asked Jul 02 '09 11:07

Rahul Vyas


People also ask

What does NSString mean?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.


2 Answers

You can use the NSString instance methods substringWithRange: or substringFromIndex:

NSString *str = @"A. rahul VyAs"; NSString *newStr = [str substringWithRange:NSMakeRange(3, [str length]-3)]; 

or

NSString *str = @"A. rahul VyAs"; NSString *newStr = [str substringFromIndex:3]; 
like image 67
Alex Rozanski Avatar answered Sep 23 '22 10:09

Alex Rozanski


This is a solution I have seen specifically for removing regularly occurring prefixes and solving the answer to the question How do I remove "A. "?

NSString * name =  @"A. rahul VyAs"; NSString * prefixToRemove = @"A. ";  name = [name stringByReplacingOccurrencesOfString:prefixToRemove withString:@""]; 

This code will remove what you tell it to remove/change if the character set exists, such as "A. ", even if the three characters (or more/less) are in the middle of the string.

If you wanted to remove rahul, you can. It's diverse in that you specify exactly what you want removed or changed, and if it exists anywhere in the String, it will be removed or changed.

If you only want a certain specified number of characters removed from the front of the text that are always random or unknown, use the [string length] method as is the top answer.

If you want to remove or change certain characters that repeatedly appear, the method I have used will enable that, similar to Wordsearch on document editors.

like image 32
App Dev Guy Avatar answered Sep 25 '22 10:09

App Dev Guy