29

I want to replace "," with a ; in my string.

For example:

Change

"Text","Text","Text",

to this:

"Text;Text;Text",

I've been trying the line.replace( ... , ... ), but can't get anything working properly.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Bobcat88
  • 738
  • 2
  • 7
  • 22

9 Answers9

46

Try this:

line.Replace("\",\"", ";")
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
DonBoitnott
  • 10,787
  • 6
  • 49
  • 68
8

The simplest way is to do

line.Replace(@",", @";");

Output is shown as below:

enter image description here

Hassan Rahman
  • 4,953
  • 1
  • 34
  • 32
7

You need to escape the double-quotes inside the search string, like this:

string orig = "\"Text\",\"Text\",\"Text\"";
string res = orig.Replace("\",\"", ";");

Note that the replacement does not occur "in place", because .NET strings are immutable. The original string will remain the same after the call; only the returned string res will have the replacements.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
6
var str = "Text\",\"Text\",\"Text";
var newstr = str.Replace("\",\"", ";");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
I4V
  • 34,891
  • 6
  • 67
  • 79
1

Use:

line.Replace(@""",""", ";");
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Si-N
  • 1,495
  • 1
  • 13
  • 27
1

Make sure you properly escape the quotes.

  string line = "\"Text\",\"Text\",\"Text\",";

  string result = line.Replace("\",\"", ";");
Rukshan Perera
  • 150
  • 2
  • 9
-1

Set your Textbox value in a string like:

string MySTring = textBox1.Text;

Then replace your string. For example, replace "Text" with "Hex":

MyString = MyString.Replace("Text", "Hex");

Or for your problem (replace "," with ;) :

MyString = MyString.Replace(@""",""", ",");

Note: If you have "" in your string you have to use @ in the back of "", like:

@"","";
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MR Coder
  • 121
  • 1
  • 3
-2

You can't use string.replace...as one string is assigned you cannot manipulate. For that, we use string builder. Here is my example. In the HTML page I add [Name] which is replaced by Name. Make sure [Name] is unique or you can give any unique name:

string Name = txtname.Text;
string contents = File.ReadAllText(Server.MapPath("~/Admin/invoice.html"));

StringBuilder builder = new StringBuilder(contents);

builder.Replace("[Name]", Name);

StringReader sr = new StringReader(builder.ToString());
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-6

Use of the replace() method

Here I'm replacing an old value to a new value:

string actual = "Hello World";

string Result = actual.Replace("World", "Stack Overflow");

----------------------
Output : "Hello Stack Overflow"
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Thivan Mydeen
  • 1,461
  • 11
  • 7