Capslock10
Capslock10

Reputation: 806

Tried replace, trim but cannot remove the quotation mark from a string C#

I am making a application which can convert a excel file to CSV file.

However, some string contain a quotation mark, so when the CSV exported, some of the String was splits to two cell which should be in one cell.

For example:

"39.6cm (15.6") HD (1366x768),97cm", "Core2 M3321" //15.6"<===have a quotation mark

I tried to use "trim(), replace(), Insert()" to remove the quotation, but it doesn't work. I don't know way.

 if (HTMLTable.Contains("\""))
 {

    HTMLTable.Trim(new Char[] {'"'}); //Try to remove quotation
    HTMLTable.Replace("\"", ""); 
    HTMLTable.Insert(HTMLTable.IndexOf('"') - 1, "\\");
 }

 csvRecord += "\",\"" + HTMLTable + "\",0"; //Append the String into the CSV builder

I tried a lot of solutions, but it doesn't work. What is the problem?

Thanks.

Upvotes: 0

Views: 156

Answers (3)

Piotr Zieliński
Piotr Zieliński

Reputation: 174

You need to know, that .Replace doesn't change existing string but return new string after replace operation.

HTMLTable = HTMLTable.Replace("\"", "");

https://msdn.microsoft.com/pl-pl/library/fk49wtc1(v=vs.110).aspx

Upvotes: 0

Stuart
Stuart

Reputation: 4258

You aren't assigning the result of the Trim or replace to a string.

You need to do something like

HtmlTable = HtmlTable.Replace("\"", string.Empty);

Looking at your comment, if you don't like string.Empty then you need to do

HtmlTable = HtmlTable.Replace("\"", "");

Upvotes: 5

Patrick Hofman
Patrick Hofman

Reputation: 156968

Since strings are immutable in .NET, you can't change their values. That means that a new string is made on every write operation on a string.

Because of that, every method which 'modifies' a string returns a new string instead. So you have to assign that value:

HTMLTable = HTMLTable.Replace("\"", ""); 

Upvotes: 2

Related Questions