代码之家  ›  专栏  ›  技术社区  ›  Ash Burlaczenko

c#-如何在正确的位置生成带“and”的字符串

  •  2
  • Ash Burlaczenko  · 技术社区  · 16 年前

    这是我到目前为止的循环

    foreach (CheckBox chk in gpbSchedule.Controls.OfType<CheckBox>())
                    {
                        if (chk.Checked)
                        {
                            //Code goes here
                        }
                    }
    

    这些复选框都有一周中几天的文本值。星期一,星期二等。

    循环将更改bool,以便知道是否至少选中了一个复选框。这将在if语句中使用,在该语句之后将显示生成的字符串,因此如果未选中任何字符串,则不会显示任何字符串。我认为这意味着,如果这有帮助的话,开始时的字符串看起来并不重要。

    先谢谢你。


    当前代码:

    string days = "*";
            foreach (CheckBox chk in gpbSchedule.Controls.OfType<CheckBox>())
            {
                if (chk.Checked)
                {
                    days += "#" + chk.Text;
                }
            }
    
            days = days.Insert(days.LastIndexOf('#'), " and ");
            days = days.Remove(days.LastIndexOf('#'), 1);
            days = days.Replace("#", ", ");
            days = days.Replace("* and ", "");
            days = days.Replace("*, ", "");
    

    有人看到这有什么问题吗?

    10 回复  |  直到 16 年前
        1
  •  3
  •   AllenG    16 年前

    我能想到的最简单的办法就是改变你的习惯 foreach for List<CheckBox> 你可以使用(没有必要,只是更直截了当地告诉我)你可以得到如下结果:

    //ckBoxes is our List<CheckBox>
    for(int i = 0; i < ckBoxes.Count; i++)
    {
      StringBuilder listBuilder = new StringBuilder;
      if(i == ckBoxes.Count -1)
      {
        listBuilder.Append("and " + dayOfWeek)
      }
      else listBuilder.Append(dayOfWeek + ", ");
    }
    

    这是非常,非常粗糙,需要大量的清洁,然后再使用它,但它应该把你的道路上的工作。

        2
  •  1
  •   kbrimington    16 年前

    var days = gpbSchecule.Controls.OfType<CheckBox>()
                                   .Where(x => x.Checked)
                                   .Select(x => x.Text)
                                   .ToArray();
    

    这将获得一个只包含选中天数的数组,您可以使用该数组来确定是否需要“and”,并对其应用简单的字符串方法。

    从这里申请 string.Join() 正如@Garo所建议的。

        3
  •  0
  •   Garo Yeriazarian Changal Rayudu    16 年前

    这样循环就可以跟踪您需要向用户显示的所有日期(以列表或其他方式)。然后,在循环之后,使用string.Join 将前N-1项与“,”和第二项组合string.Join 将最后一项添加为“and”。

        4
  •  0
  •   unholysampler    16 年前

    List<CheckBox> checked = new List<CheckBox>();
    foreach (CheckBox chk in gpbSchedule.Controls.OfType<CheckBox>())
    {
        if (chk.Checked)
        {
            checked.Add(chk);
        }
    }
    for(int i = 0; i < checked.Count; i++)
    {
        if (i == checked.Count-1))
        {
            //write for last element
        }
        else
        {
            //write for all other elements
        }
    }
    
        5
  •  0
  •   Ronald Wildenberg    16 年前

    var days = new List<string>();
    foreach (CheckBox chk in gpbSchedule.Controls.OfType<CheckBox>())
    {
        if (chk.Checked)
        {
            days.Add(chk.Text);
        }
    }
    string daysString = "";
    if (days.Count == 1)
    {
        daysString = days[0];
    }
    else if (days.Count > 1)
    {
        daysString =
            string.Join(", ", days.Take(days.Count - 1)) +
            " and " +
            days[days.Count - 1];
    }
    
        6
  •  0
  •   rui    16 年前

    有点难看的解决办法,但应该管用。

    string result = "";
    string nextDay = null;
    foreach (CheckBox chk in gpbSchedule.Controls.OfType<CheckBox>())
    {
        if (nextDay != null) {
          if (result.length() > 0) {
            result += ", " + nextDay;
          } else {
            result = nextDay;
          }
          nextDay = null;
        }
        if (chk.Checked)
        {
            //Code goes here
            nextDay = chk.text; // Your text here Monday, Tuesday, ...
        }
    }
    
    if (nextDay != null) {
      if (result.length() > 0) {
        result += " and " + nextDay;
      } else {
        result = nextDay;
      }
      nextDay = null;
    }
    
        7
  •  0
  •   Dave White John Alexiou    16 年前
        // change this into a collection of your checked group boxes
        string[] threeStrings = new string[] { "Joe", "Jim", "Robert" };
        StringBuilder newString = new StringBuilder();
    
        // iterate over your array here - strings used to simplify example
        for (int i = 0; i < threeStrings.Length; i++)
        {
            if (i < threeStrings.Length - 1)
            {
                newString.Append(threeStrings[i]);
                newString.Append(", ");
            }
            else
            {
                newString.Append(" and ");
                newString.Append(threeStrings[i]);
            }
        }
        Console.WriteLine(newString.ToString());
    
        8
  •  0
  •   mdm20    16 年前

    这是另一个解决方案。我放了一些初始化代码来测试它。

    private List<CheckBox> _checkBoxes;
    
    private void Test()
    {
        Init();
    
        List<CheckBox> checkedCheckBoxes = _checkBoxes.Where(cb => cb.Checked == true).ToList();
        StringBuilder str = new StringBuilder();
        string delimiter = String.Empty;
    
        for (int i = 0; i < checkedCheckBoxes.Count; i++)
        {
            str.Append(delimiter);
            str.Append(checkedCheckBoxes[i].Name);
    
            if (i != checkedCheckBoxes.Count)
            {
                if (i == checkedCheckBoxes.Count - 2)
                    delimiter = " and ";
                else
                    delimiter = ", ";
            }
        }
    
        Console.WriteLine(str.ToString());
        Console.ReadLine();
    }
    
    private void Init()
    {
        _checkBoxes = new List<CheckBox>();
    
        string[] days = new string[7] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
        Random r = new Random();
    
        foreach (string day in days)
        {
            CheckBox cb = new CheckBox();
            cb.Name = day;
            cb.Checked = Convert.ToBoolean(r.Next(0, 2));
            _checkBoxes.Add(cb);
        } 
    }
    
        9
  •  0
  •   Danny T.    16 年前

    我投了阿伦的票,但你也可以这样做:

    // First build a string of days separated by a coma
    string days = String.Empty;
    foreach (CheckBox chk in gpbSchedule.Controls.OfType<CheckBox>())
    {
        if (chk.Checked)
        {
            if (!String.IsNullOrEmpty(days))
                days += ", ";
            days += chk.Text;            
        }
    }
    
    // Then replace the last coma with "and"            
    int lastComaIndex = days.LastIndexOf(',');
    if (lastComaIndex >= 0)
        days = days.Substring(0, lastComaIndex) + " and " + days.Substring(lastComaIndex + 2);
    
        10
  •  0
  •   Gabe Timothy Khouri    16 年前

    以下是我的看法:

    var darr = (from checkbox in gpbSchecule.Controls.OfType<CheckBox>()
                where checkbox.Checked
                select checkbox.Text)
               .ToArray();
    
    string days = "";
    if (darr.Length > 0)
    {
        days = string.Join(", ", darr.Take(darr.Length - 1));
        if (darr.Length > 1)
            days += " and ";
        days += darr[darr.Length - 1];
    }