Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone remove substring from string

Hi I have a string like that

NSString *str=@"1,2,3,4"; 

I have to remove any character from it dynamically. For example, @"3,".

like image 637
Maddy Avatar asked May 24 '12 10:05

Maddy


People also ask

How do you remove a substring from a string?

To remove a substring from a string, call the replace() method, passing it the substring and an empty string as parameters, e.g. str. replace("example", "") . The replace() method will return a new string, where the first occurrence of the supplied substring is removed.

How do I remove the last two characters from a string in Swift?

Swift String dropLast() The dropLast() method removes the last character of the string.

How do I remove a character from a string in Swift?

To remove the specific character from a string, we can use the built-in remove() method in Swift. The remove() method takes the character position as an argument and removed it from the string.

How do I remove the first character from a string in Swift?

Swift String dropFirst() The dropFirst() method removes the first character of the string.


2 Answers

NSString *str=@"1,2,3,4"; [str stringByReplacingOccurrencesOfString:@"3," withString:@""]; 

That will remove ALL occurrences of @"3," in str.

If you want to remove only the first occurrence of @"3,":

NSString* str = @"1,2,3,4"; NSRange replaceRange = [str rangeOfString:@"3,"]; if (replaceRange.location != NSNotFound){     NSString* result = [str stringByReplacingCharactersInRange:replaceRange withString:@""]; } 

Hope this helps.

like image 137
sonxurxo Avatar answered Sep 20 '22 16:09

sonxurxo


  NSString *str=@"1,2,3,4";   int numberToRemove = 4;   str = [str stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%d",numberToRemove] withString:@""];  str = [str stringByReplacingOccurrencesOfString:@",," withString:@","]; 

This will help.

like image 34
Suresh Varma Avatar answered Sep 19 '22 16:09

Suresh Varma