C # smart way to remove multiple occurrences of a character in a string

My program reads a file that contains thousands of lines of the following type: "Timestamp", "LiveStandby", "Total1", "Total2", "Total3", etc. each line is different. What is the best way to split and remove the "" and also put the values ​​in a list

this is what i have

 while ((line = file.ReadLine()) != null)
  {
     List<string> title_list = new List<string>(line.Split(',')); 
  }

the above step still does not contain the removal of quotes. I can do foreach, but it seems to defeat the goal of having List and Split in just 1 line. What is the best and smartest way to do this?

+3
source share
5 answers

Keeping this simple, how it should work:

List<string> strings = new List<string>();
while ((line = file.ReadLine()) != null) 
    string.AddRange(line.Replace("\"").split(',').AsEnumerable());
+2
source

, , , CSV, FileHelpers.

, FileHelpers:

, :

[DelimitedRecord(",")]
public class MyDataRecord
{
    [FieldQuoted('"')]
    public string TimeStamp;
    [FieldQuoted('"')]
    public string LiveStandby;
    [FieldQuoted('"')]
    public string Total1;
    [FieldQuoted('"')]
    public string Total2;
    [FieldQuoted('"')]
    public string Total3;
}

:

var csvEngine = new FileHelperEngine<MyDataRecord>(Encoding.UTF8)
    { 
        Options = { IgnoreFirstLines = 1, IgnoreEmptyLines = true }
    };

var parsedItems = csvEngine.ReadFile(@"D:\myfile.csv");

, , . , , - .

+4

. , (.. EXCEL ), , .

, , - , :

"column 1", 2, 0104400, $1,300, "This is an interestion question, he said"

.. , .., .

, , , , .

, , , , , CSV , . , , ​​ , . , . csv , , .

If this is the case, and you just want to strip the quotes after comma separation, then try a little linq. It can also be expanded to replace specific characters that you worry about.

line.Split(',').Select(i => i.Replace("\"", "")).ToArray()

Hope to clarify all conflicting tips.

+2
source

You can use the function Array.ConvertAll().

string line = "\"Timestamp\",\"LiveStandby\",\"Total1\",\"Total2\",\"Total3\"";

var list = new List<String>(Array.ConvertAll(line.Split(','), x=> x.Replace("\"","")));
+1
source

Perform Replace first, then Split into your list. Here is your replacement code.

while ((line = file.ReadLine()) != null)   
{      
  List<string> title_list = new List<string>(line.Replace("\"", "").Split(','));    
}

Although you will need a variable to hold all lists, look at using AddRange ().

0
source

All Articles