迭代字符串列表C#

时间:2011-11-09 09:08:25

标签: c# list

我需要通过迭代字符串列表

来构建一个字符串

我的输入是List<string>,下面是3个可能输入的示例:

case 1        case2      case3
  5             5          ""
  +             +          +
  6             6          6
  +             +          +
  9             9          9
  -             -          -
  8             ""         8
  +             +          +
  1             1          1

上述每个示例案例的所需结果输出应如下所示(每个都是单个字符串值):

案例1:"5+6+9-8+1"

案例2:"5+6+9+1"(因为9之后的值是“”,不应该考虑它,前面的运算符也应该被忽略)

案例3:"6+9-8+1"(因为第一个值是“”它不应该被认为是它,并且也应该忽略跟随运算符)

2 个答案:

答案 0 :(得分:4)

我假设输入列表中的每个其他字符串都是运算符。然后你可以这样做......

//from another function
string[] inputList = new string[] { "5", "+", "6", "+", "9", "-", "8", "+", "1" };
string result = JoinList(inputList);

//function to join list
public string JoinList(string[] inputList){
    if(inputList.Length == 0)
        return "";

    List<string> list = new List<string>();

    int start = 0;
    if (string.IsNullOrEmpty(inputList[0]))
        start = 2;

    for (int i = start; i < inputList.Length; i++)
    {
        string s = inputList[i];

        if (string.IsNullOrEmpty(s))
        {
            if (list.Count > 0)
                list.RemoveAt(list.Count - 1);
            continue;
        }

        list.Add(s);
    }

    return string.Join("", list);
}

答案 1 :(得分:2)

根据我的理解(=您输入了List<String>,并希望输出String):

List<String> str = new List<String> {"5", "+", "6", "+", "9", "-", "", "+", "1"};
String case1 = "";
str.ForEach(x => case1 += x);
case1 = Regex.Replace(case1, @"(?<![0-9])(\+|-)", "");

会给你:case1 = "5+6+9+1"

相关问题