2013-03-29 40 views
-3

我怎樣才能分割這個空白。 (第一行是其報頭)如何在C#中用空格分隔字符串?

enter image description here

我嘗試這種代碼,但錯誤「索引超出範圍」在cbay.ABS = columnsC [5]因爲第二線返回的僅4而不是像6層的元件在第一行。我想第二行也返回6個元素。

using (StringReader strrdr = new StringReader(strData)) 
{ 
    string str; 
    while ((str = strrdr.ReadLine()) != null) 
    { 
     // str = str.Trim(); 
     if ((Regex.IsMatch(str.Substring(0, 1), @"J")) || (Regex.IsMatch(str.Substring(0, 1), @"C"))) 
     { 
      columnsC = Regex.Split(str, " +"); 
      cbay.AC = columnsC[1]; 
      cbay.AU = columnsC[2]; 
      cbay.SA = columnsC[3]; 
      cbay.ABS = columnsC[5]; 
      // cbay.ABS = str; 
     } 
    } 
} 
+0

也許除了我以外大家都明白的問題,但我不知道。 – JohnB

+0

你可以測試String.IsNullOrWhiteSpace(cbay.AC)而不是cbay.AC == null – Xaruth

回答

2

爲了獲得唯一的話沒有冗餘witespaces你可以通過StringSplitOptions.RemoveEmptyEntries作爲stringSplit方法第二個參數,如果將刪除所有多餘的「空格」,因爲它會在每個空格分開。使用正則表達式檢查這個簡單的例子,而不是:

string inputString = "Some string with words  separated with multiple blanck characters"; 
string[] words = inputString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 
string resultString = String.Join(" ", words); //joins the words without multiple whitespaces, this is for test only. 

編輯你的具體情況,如果你使用這個字符串,其中部分與多個空格分開的(至少三個),它會工作。檢查例子:

string inputString = "J 16 16 13 3 3"; 
string[] words = inputString.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 

EDIT2:這是最簡單和dummiest解決您的問題,但我認爲它會工作:

if(str.Length>0 && ((str[0]=="J") || (str[0]=="C"))) 
{ 
    columnsC = str.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); 
    if((str[0]=="J") 
    { 
      cbay.AC = columnsC[1]; 
      cbay.AU = columnsC[2]; 
      cbay.SA = columnsC[3]; 
      cbay.ABS = columnsC[5]; 
    } 
    else 
    { 
      cbay.AU = columnsC[1]; 
      cbay.SA = columnsC[2]; 
    } 
} 
+0

我知道,但我希望每行都返回6個元素。謝謝。 – user979637

+0

你有沒有試過這段代碼?它會返回給你六絃。只需使用'columnsC = str.Split(new char [] {''},StringSplitOptions.RemoveEmptyEntries);'而不是你的代碼。 –

+0

是的,我試過了,它返回6個元素,但是所有值=空,它必須是值:C,空,8,8,0,在第二行空 – user979637

0

你可以先用零和替換後的多個空格在剩餘的單個空間上分裂;

 var test = "test 1 2 3"; 
     var items = test.Replace(" ", "0").Split(' '); 

如果有很多的空間你可能會得到一些00位,但仍然會工作,我猜

+0

謝謝,但這不起作用 – user979637

相關問題