Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String find and replace

Tags:

c#

I have a string like

string text="~aaa~bbb~ccc~bbbddd";

The input value will be : bbb

So in the above string i should remove the value "~bbb"

The resulting string should be

text="~aaa~ccc~bbbddd";
like image 452
Vetti85 Avatar asked May 05 '26 05:05

Vetti85


2 Answers

I'm not sure what are you wanna do but if i've got it you can do this :

private string ReplaceFirstOccurrence(string Source, string Find, string Replace)
{
 int Place = Source.IndexOf(Find);
 string result = Source.Remove(Place, Find.Length).Insert(Place, Replace);
 return result;
}

var result =ReplaceFirstOccurrence(text,"~"+input,"");
like image 57
hm1984ir Avatar answered May 06 '26 18:05

hm1984ir


One way would be:

string text = "~aaa~bbb~ccc~bbbddd";
string newStr = string.Join("~", text.Split('~').Where(r => r != "bbb"));

But if performance is the consideration then consider some other solution

like image 20
Habib Avatar answered May 06 '26 17:05

Habib