2013-04-24 232 views
-7

我有一個獲取字符串的代碼,該字符串包含顏色名稱。我想分割用逗號分隔的字符串。這裏是我的代碼。用逗號分隔的字符串

public static string getcolours() 
{ 
    string str = null; 
    DBClass db = new DBClass(); 
    DataTable allcolours = new DataTable(); 
    allcolours = db.GetTableSP("kt_getcolors"); 
    for (int i = 0; i < allcolours.Rows.Count; i++) 
    { 
     string s = allcolours.Rows[i].ItemArray[0].ToString(); 
     string missingpath = "images/color/" + s + ".jpg"; 
     if (FileExists(missingpath)) 
     { 

     } 
     else 
     { 
      str = str + missingpath; 


     } 

    } 
    return str; 

} 
+0

試着向上看「C#string split」。 - http://msdn.microsoft.com/en-us/library/tabh47cf.aspx – 2013-04-24 14:56:13

+0

string.Split(',') – Indy9000 2013-04-24 14:56:38

+2

只是谷歌你的標題... – ken2k 2013-04-24 14:57:02

回答

3

只需使用Split

string[] yourStrings = s.Split(','); 

其實,我覺得你要求的是返回字符串像這樣:

"red, blue, green, yellow" 

爲了實現這個目標,你需要使用string.Join。試試這個:

public static string getcolours() 
{ 
    List<string> colours = new List<string>(); 
    DBClass db = new DBClass(); 
    DataTable allcolours = new DataTable(); 
    allcolours = db.GetTableSP("kt_getcolors"); 
    for (int i = 0; i < allcolours.Rows.Count; i++) 
    { 
     string s = allcolours.Rows[i].ItemArray[0].ToString(); 
     string missingpath = "images/color/" + s + ".jpg"; 
     if (!FileExists(missingpath)) 
     { 
      colours.Add(missingpath); 
     } 
    } 

    return string.Join(", ", colours); 
} 
+0

但它不返回你的字符串值。 – user2264616 2013-04-24 14:58:04

+0

@ user2264616你想返回字符串列表嗎? – mattytommo 2013-04-24 14:58:49

+0

@Jodrell只是一個變量名,它可以更改爲任何內容。 – mattytommo 2013-04-24 15:00:31

1
string[] words = s.Split(','); 
0

如果你不希望有空值,使用StringSplitOptions。

var colours = str.Split(",", StringSplitOptions.RemoveEmptyEntries); 
+0

但是我不能返回instr的return str。 – user2264616 2013-04-24 15:07:11