2017-02-03 128 views
1

我有這樣C#字符串解析

string temp = "'ADDR_LINE_2','MODEL','TABLE',5,'S','Y','C40','MUL,NBLD,NITA,NUND','','Address line 2'" 

每對單引號的字符串是由逗號分隔的字段。我想清空字符串中的第8個字段。我不能簡單地做replace("MUL,NBLD,NITA,NUND",""),因爲該字段可能包含任何內容。還請注意第4場是一個數字,因此沒有單獨的報價,大約在5

我該如何做到這一點?

+0

當你說_empty_你想要一個沒有任何內容的兩個逗號分隔的第八個字段,或者你想完全刪除它嗎? – Steve

回答

4
static void Main() 
{ 
    var temp = "'ADDR_LINE_2','MODEL','TABLE',5,'S','Y','C40','MUL,NBLD,NITA,NUND','','Address line 2'"; 

    var parts = Split(temp).ToArray(); 
    parts[7] = null; 
    var ret = string.Join(",", parts); 

    // or replace the above 3 lines with this...   
    //var ret = string.Join(",", Split(temp).Select((v,i)=>i!=7 ? v : null)); 

    //ret == "'ADDR_LINE_2','MODEL','TABLE',5,'S','Y','C40',,'','Address line 2'" 
} 

public static IEnumerable<string> Split(string input, char delimiter = ',', char quote = '\'') 
{ 
    string temp = ""; 
    bool skipDelimiter = false; 

    foreach (var c in input) 
    { 
     if (c == quote) 
      skipDelimiter = !skipDelimiter; 
     else if (c == delimiter && !skipDelimiter) 
     { 
      //do split 
      yield return temp; 
      temp = ""; 
      continue; 
     } 

     temp += c; 
    } 
    yield return temp; 
} 
+0

感謝您的快速回答。這工作! – Shawn

1

我在下面做了一個小實現。我解釋評論中的邏輯。基本上你想寫一個簡單的解析器來完成你所描述的內容。

edit0:剛剛意識到我做了你問現在oops..fixed

EDIT1相反:更換與空字符串,而不是從逗號分隔的列表消除了整場。

static void Main(string[] args) 
    { 
     string temp = "'ADDR_LINE_2','MODEL','TABLE',5,'S','Y','C40','MUL,NBLD,NITA,NUND','','Address line 2'"; 
     //keep track of the single quotes 
     int singleQuoteCount= 0; 
     //keep track of commas 
     int comma_count = 0; 
     String field = ""; 
     foreach (Char chr in temp) 
     { 
      //add to the field string if we are not between the 7th and 8th comma not counting commas between single quotes 
      if (comma_count != 7) 
       field += chr; 
      //plug in null string between two single quotes instead of whatever chars are in the eigth field. 
      else if (chr == '\'' && singleQuoteCount %2 ==1) 
       field += "\'',"; 

      if (chr == '\'') singleQuoteCount++; 
      //only want to add to comma_count if we are outside of single quotes. 
      if (singleQuoteCount % 2 == 0 && chr == ',') comma_count++; 

     } 
    } 
-1

如果你會用 ' - ' 字段(考試: 'MUL-NBLD-NITA-NUND')內,而不是(或其它字符) '',你可以使用此代碼:

static void Main(string[] args) 
    { 
     string temp = "'ADDR_LINE_2','MODEL','TABLE',5,'S','Y','C40','MUL-NBLD-NITA-NUND','','Address line 2'"; 
     temp = replaceField(temp, 8); 
    } 

    static string replaceField(string list, int field) 
    { 
     string[] fields = list.Split(','); 
     string chosenField = fields[field - 1 /*<--Arrays start at 0!*/]; 

     if(!(field == fields.Length)) 
      list = list.Replace(chosenField + ",", ""); 
     else 
      list = list.Replace("," + chosenField, ""); 

     return list; 
    } 

    //Return-Value: "'ADDR_LINE_2','MODEL','TABLE',5,'S','Y','C40','','Address line 2'"