How to remove first 3 characters from NSString?

Objective CNsstring

Objective C Problem Overview


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?

Objective C Solutions


Solution 1 - Objective C

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];

Solution 2 - Objective C

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.

Solution 3 - Objective C

Try this,

char *string=[@"A. rahul VyAs" cStringUsingEncoding:NSUTF8StringEncoding];
char *subString=&name[3];
NSString *newString=[NSString stringWithCString:subString encoding:NSUTF8StringEncoding];

Solution 4 - Objective C

It's this simple:

myString = [myString subStringFromIndex:3]

That's it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRahul VyasView Question on Stackoverflow
Solution 1 - Objective CAlex RozanskiView Answer on Stackoverflow
Solution 2 - Objective CApp Dev GuyView Answer on Stackoverflow
Solution 3 - Objective CrakeshNSView Answer on Stackoverflow
Solution 4 - Objective CAlex ZavatoneView Answer on Stackoverflow