Reputation: 5150
I am trying to allow people to throw account number into a text box and I am trying to let them enter them in several different way
IE:
1234 5678 9101 1213
Or:
1234,5678,9101,1112
But for some reason my Replace function doesn't want to respect Environment.Newline or "\r\n"
public string[] getAccounts()
{
string textLines;
string[] accounts;
textLines = accountsTextBox.Text;
textLines.Replace(Environment.NewLine, ",");
accounts = textLines.Split(Environment.NewLine.ToArray(), StringSplitOptions.RemoveEmptyEntries);
return accounts;
}
I grab everything from the text box into a string, then want to force everything into a comma delimited list, and finally split that list by commas.
What am I missing in my Replace?
Upvotes: 1
Views: 3106
Reputation: 8047
This is because String.Replace does not modify the original string, but rather, returns a new string. You should update the line
textLines.Replace(Environment.NewLine, ",");
as follows:
textLines = textLines.Replace(Environment.NewLine, ",");
Additionally, you have another issue with your call to String.Split()
:
It is trying to split on Environment.NewLine.ToArray()
. Assuming you did your replace correctly, it should have already replaced your newline characters with commas at this point, so there would be no newline delimiters left in the string.
My ultimate recommendation would be the following:
// At the class level
static char[] delimiters = new char[]{','};
// In your getAccounts() function
textLines = accountsTextBox.Text.Replace(Environment.NewLine, ",");
accounts = textLines.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
Alternately, you could forgo the call to String.Replace()
altogether and just update your delimiter array, like so:
// At the class level
static char[] delimiters = ("\r\n,").ToArray(); // treat '\r' '\n' and ',' as delimiters
// In your getAccounts() function
accounts = accountsTextBox.Text.Split(delimiters, StringSplitOptions.RemoveEmptyEntries);
Upvotes: 7