C# - split method - cannot convert char to string

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DaveRook
    New Member
    • Jul 2007
    • 147

    #1

    C# - split method - cannot convert char to string

    Hi

    I've had a few error messages with this I don't understand why. It works fine in a Windows Form, but now moving it to a website, it's not working. I don't have the option to count the lines as I did with Windows Forms so I assume the best way is to use the split method. However, the split method only returns Character Arrays, and I want a string, so am calling the split from the Text.RegularExp ression namespace.

    I am trying to split the lines entered into a multiline textbox line by line, and then peform some logic in each array.

    I am told it can't convert char to string.

    My code

    Code:
                string[] arrS = System.Text.RegularExpressions.Regex.Split(txtS.Text,Environment.NewLine);
                foreach(string st in Convert.ToString(arrS))
                {
                         //code
                }
    Any ideas what I've done wrong? Or is the foreach loop only reads strings?
  • Ravi L
    New Member
    • Oct 2010
    • 12

    #2
    It should have ideally been as below:

    foreach(string st in arrS)
    {
    //code
    }

    Comment

    • DaveRook
      New Member
      • Jul 2007
      • 147

      #3
      I did that originally, same error. I only added the Convert.ToStrin g due to the cannot convert type char to string error message.

      Any other ideas?

      Comment

      • Aimee Bailey
        Recognized Expert New Member
        • Apr 2010
        • 197

        #4
        Are you sure the error you recieved before adding Convert.ToStrin g was on the line you modified? I can't see how an element of string[] would ever be treated as a char. Anyway, instead of using regex, why don't you just use the split method built into the string class:

        Code:
        string[] arrS = txtS.Text.Split(new string[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
        foreach(string s in arrS)
        {
        
        }

        Comment

        Working...