简体   繁体   English

从列表框项目中拆分字符串

[英]splitting string from listbox items

i am listbox to store different strings which user gives as input. 我是列表框,用于存储用户输入的不同字符串。 but i want to split those listbox items where i want to have the first word of every item as seperate string and rest as other string. 但我想拆分这些列表框项目,在这些项目中,我希望每个项目的第一个单词都作为单独的字符串,而其余部分与其他字符串一样。 i am iterating the listbox item as 我将列表框项迭代为

foreach (ListItem item in lstboxColumnList.Items)
            {

                column_name = temp + "\" "+item+"\"";
                temp = column_name + "," + Environment.NewLine;
            }

how could i get the splitted string 我怎么能得到分割的字符串

Assuming firs word ends with a space, you can use something like below: 假设冷杉词以空格结尾,则可以使用如下所示的内容:

string firsWord = sentence.SubString(0, sentence.IndexOf(' '));
string remainingSentence = sentence.SubString(sentence.IndexOf(' '), sentence.Length);

I dont know your listbox item's format.. but I assumed that your listbox item have at least 2 word and separate by a space.. so, you can do the splitting using substring and index of.. 我不知道您的列表框项目的格式..但是我假设您的列表框项目至少有2个字,并以空格分隔。.因此,您可以使用。的子字符串和索引进行拆分。

string first = sentence.SubString(0, sentence.IndexOf(" "));
string second = sentence.SubString(sentence.IndexOf(" ") + 1);
    public void Test()
    {
        List<string> source = new List<string> {
            "key1 some data",
            "key2 some more data",
            "key3 yada..."};
        Dictionary<string, string> resultDictionary = source.ToDictionary(n => n.Split(' ').First, n => n.Substring(n.IndexOf(' ')));
        List<string> resultStrings = source.Select(n => string.Format("\"{0}\",{1}", n.Split(' ').First, n.Substring(n.IndexOf(' ')))).ToList;
    }

resultDictionary is a dictionary with the key set to the first word of each string in the source list. resultDictionary是一个字典,其关键字设置为源列表中每个字符串的第一个单词。

The second closer matches the requirements in your question that it outputs a list of strings in the format you specified. 第二个更接近的查询符合您的问题要求,即以您指定的格式输出字符串列表。

EDIT: Apologies, posted in VB first time round. 编辑:道歉,第一次发布在VB中。

checkout: 查看:

 var parts = lstboxColumnList.Items.OfType<ListItem>().Select(i => new { 
                          Part1 = i.Text.Split(' ').FirstOrDefault(),
                          Part2 = i.Text.Substring(i.Text.IndexOf(' '))
                       });

 foreach (var part in parts)
 {
     var p1 = part.Part1;
     var p2 = part.Part2;

     // TODO: use p1, p2 in magic code!!
 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM