如何分离字符串数组的字符串 [英] How to separate the strings of string array

查看:99
本文介绍了如何分离字符串数组的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





string [] GWMsgDetails = new string [4];



GWMsgDetails是一个大小为4的字符串数组.GWMsgDetails中可能不总是有4个元素。这取决于用户选择。







我试图通过使用来分隔字符串数组的字符串符号,



Hi,

string[] GWMsgDetails = new string[4] ;

GWMsgDetails is a string array of size 4. There may not be always 4 elements in GWMsgDetails. It depends on user selection.



I am trying to separate the strings of string array by using a symbol ","

foreach (GatewayMessageDetails temp in GWMsgDetails)
                {
                    
          Constants.GT_EXCEL_WR_HEX_GATEWAYBUSES_INDEX] = string.Join(",", temp.GatewayBuses);  
                                        
                            RowIndex++;
                  
                }





如果数组中只有2个元素,如红色和黄色。其他2个元素都是null。

然后我在excel表(行)中得到类似下面的内容





红色,黄色,,



如何避免excel表格末尾的逗号(,,)???





谢谢

John



When there are only 2 elements in array like Red and Yellow. The other 2 elements are null.
Then I am getting something like below in excel sheet(row)


Red,Yellow,,

How to avoid the commas(,,) at the end in excel sheet???


Thanks
John

推荐答案

您可以使用foreach,而不是使用foreach for循环的上限设置为GWMsgDetails.length-1



然后检查它是否不是string.Empty,如果它不是那么只执行你的逻辑,否则打破。



希望它有所帮助。
Instead of using foreach, you may use the for loop with an upper limit set as GWMsgDetails.length-1

Then check if it is not string.Empty and if it is not then only carry out your logic, else break.

Hope it helps.


你可以应用一些LINQ,就像这样



You could apply some LINQ to it, like so

string value = String.Join(",", temp.GatewayBuses.Where(s => !String.IsNullOrEmpty(s)).ToArray())





这将过滤掉所有空或空的字符串。



您也可以在循环中编写它:



This will filter out all strings that are null or empty.

You could also just write it in a loop though:

StringBuilder sb = new StringBuilder();
for (int i = 0, len = temp.GatewayBuses.Length; i < len; ++i)
{
    string s = temp.GatewayBuses[i];
    if(String.IsNullOrEmpty(s)) continue;
    
    if(i != 0) sb.Append(",");
    sb.Append(s);
}
string value = sb.ToString();


尝试如下。



注意:我没试过这个请检查一下。



Try is as below.

Note: I didn't test this.Please check that.

string stringToCheck = "";

foreach (GatewayMessageDetails temp in GWMsgDetails)
    {

  if (!temp.Contains(stringToCheck))
    {
     Constants.GT_EXCEL_WR_HEX_GATEWAYBUSES_INDEX] = string.Join(",", temp.GatewayBuses);

     RowIndex++;
   }

}


这篇关于如何分离字符串数组的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆