2013-04-24 237 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