How to break a string at each comma?

前端 未结 6 1877
再見小時候
再見小時候 2021-01-24 15:11

Hi guys I have a problem at hand that I can\'t seem to figure out, I have a string (C#) which looks like this:

string tags = \"cars, motor, whee         


        
6条回答
  •  悲&欢浪女
    2021-01-24 15:53

    You can use one of String.Split methods

    Split Method (Char[])
    Split Method (Char[], StringSplitOptions)
    Split Method (String[], StringSplitOptions)
    

    let's try second option: I'm giving , and space as split chars then on each those character occurrence input string will be split, but there can be empty strings in the results. we can remove them using StringSplitOptions.RemoveEmptyEntries parameter.

    string[] tagArray = tags.Split(new char[]{',', ' '},
                                   StringSplitOptions.RemoveEmptyEntries);
    

    OR

     string[] tagArray = s.Split(", ".ToCharArray(), 
                                   StringSplitOptions.RemoveEmptyEntries);
    

    you can access each tag by:

    foreach (var t in tagArray )
    {
        lblTags.Text = lblTags.Text + " " + t; // update lable with tag values 
        //System.Diagnostics.Debug.WriteLine(t); // this result can be see on your VS out put window 
    }
    

提交回复
热议问题