开发者

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..

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.

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.


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!!
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜