Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the exact occurence of characters from a string?

Tags:

c#

.net

asp.net

For Example, I have a string like :

string str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";

I want to delete the charaters ,phani from str.

Now, I am using str = str.Replace(",phani", string.Empty);

then my output is : str="santhosh,ravi123,praveen,sathish,prakash";

But I want a output like : str="santhosh,ravi,phani123,praveen,sathish,prakash";

like image 400
RealSteel Avatar asked Mar 06 '13 10:03

RealSteel


People also ask

How do I remove a specific character from a string?

Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.

How do I remove a specific character from a string in regex?

If you are having a string with special characters and want's to remove/replace them then you can use regex for that. Use this code: Regex. Replace(your String, @"[^0-9a-zA-Z]+", "")

How do I remove all occurrences from a char in a string python?

Python Remove Character from String using replace() We can use string replace() function to replace a character with a new character. If we provide an empty string as the second argument, then the character will get removed from the string.

How do you remove all occurrences of a character from a string in C?

Logic to remove all occurrences of a characterRun a loop from start character of str to end. Inside the loop, check if current character of string str is equal to toRemove. If the mentioned condition is true then shift all character to one position left from current matched position to end of string.


2 Answers

string str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
var words = str.Split(',');
str = String.Join(",", words.Where(word => word != "phani"));
like image 74
Silvermind Avatar answered Sep 17 '22 18:09

Silvermind


the better choice is to use a Split and Join method. Easy in Linq :

String str = "santhosh,phani,ravi,phani123,praveen,sathish,prakash";
String token = "phani";
String result = String.Join(",", str.Split(',').Where(s => s != token));

(edit : I take time for testing and i'm not first ^^)

like image 45
Xaruth Avatar answered Sep 19 '22 18:09

Xaruth