2

如果我的代码像这样item,如何忽略第一个string[]if (item=="")

string[] temp3 = clearstring.Split(new string[]{@",","\r\n","\n","]", "\"", "}"}, StringSplitOptions.None);
temp.Close();

StreamWriter sW = new StreamWriter(Npath);

foreach (string item in temp3)
{
    if (item == "")
    {
    }
4

6 回答 6

3

使用StringSplitOptions.RemoveEmptyEntries

string[] temp3 = clearstring.Split(new string[]{@",","\r\n","\n","]", "\"", "}"}, StringSplitOptions.RemoveEmptyEntries);

编辑:仅输入第一个空字符串的选项:

for(int i=0; i<temp3.Length; i++)
{
    string item = temp3[i];
    if(i==0 && item == string.Empty)
       continue;

    //do work
}
于 2013-03-28T12:02:18.703 回答
1

您应该使用continue关键字。

话虽如此,您可能应该使用String.IsNullOrEmpty方法,而不是自己检查“”。

if (String.IsNullOrEmpty(item))
{
   continue;
}
于 2013-03-28T11:58:41.377 回答
0

见下文。您可以使用 continue 关键字。

for (int i=0; i < temp3.Length; i++)
    {
                        if (i == 0 && item3[i] == "")
                        {
                           continue;
                        }
   }
于 2013-03-28T11:58:50.640 回答
0
string[] temp3 = clearstring.Split(new string[]{@",","\r\n","\n","]", "\"", "}"}, StringSplitOptions.None);
temp.Close();

StreamWriter sW = new StreamWriter(Npath);

int i = 0;
foreach (string item in temp3)
{
    if (item == string.empty && i == 0)
    {
        continue;
    }
    // do your stuff here
    i++;
}
于 2013-03-28T12:10:22.197 回答
0

你提到如果它是空的,你需要先跳过,最后跳过

string[] temp3 = clearstring.Split(new string[]{@",","\r\n","\n","]", "\"", "}"}, StringSplitOptions.None);
temp.Close();

StreamWriter sW = new StreamWriter(Npath);

for (int i=0; i< temp3.Length; i++)
{
    if ((i == 0 || i == temp3.Length-1) && string.IsNullOrEmpty(temp3[i]))
       continue;
    //do your stuff here
}
于 2013-03-28T12:10:53.153 回答
0

为了完整起见,这里有几个 Linq 答案:

var stringsOmittingFirstIfEmpty = temp3.Skip(temp3[0] == "" ? 1 : 0);

var stringsOmittingFirstIfEmpty = temp3.Skip(string.IsNullOrEmpty(temp3[0]) ? 1 : 0);

var stringsOmittingFirstIfEmpty = temp3.Skip(1-Math.Sign(temp3[0].Length)); // Yuck! :)

我认为我实际上不会使用其中任何一个(尤其是最后一个,这真是个笑话)。

我可能会去:

bool isFirst = true;

foreach (var item in temp3)
{
    if (!isFirst || !string.IsNullOrEmpty(item))
    {
        // Process item.
    }

    isFirst = false;
}

或者

bool isFirst = true;

foreach (var item in temp3)
{
    if (!isFirst || item != "")
    {
        // Process item.
    }

    isFirst = false;
}

甚至

bool passedFirst = false;

foreach (var item in temp3)
{
    Contract.Assume(item != null);

    if (passedFirst || item != "")
    {
        // Process item.
    }

    passedFirst = true;
}
于 2013-03-28T12:40:54.343 回答