I am trying to use Trim()
on a multi line string, however only the first line will Trim()
. I can't seem to figure out how to remove all white space from the beginning of each line.
string temp1 = " test ";
string temp2 = @" test
line 2 ";
MessageBox.Show(temp1.Trim());
//shows "test".
MessageBox.Show(temp2.Trim());
//shows "test"
" line2 ".
Can I use Trim
/TrimStart
/TrimEnd
on a multi line string?
You can use the . split() method and the . join() method together to split a string into multiple lines.
Click the Display tab. To enable multiple lines of text to be typed in the text box, select the Multi-line check box, and then optionally do one of the following: To prevent users from being able to insert paragraph breaks in the text box by pressing ENTER, clear the Paragraph breaks check box.
The Trim() method in C# is used to return a new string in which all leading and trailing occurrences of a set of specified characters from the current string are removed.
Can I use Trim/TrimStart/TrimEnd on a multi line string?
Yes, but it only Trims the string as a whole, and does not pay attention to each line within the string's content.
If you need to Trim each line, you could do something like:
string trimmedByLine = string.Join(
"\n",
temp2.Split('\n').Select(s => s.Trim()));
This trims each line
temp2 = string.Join(Environment.NewLine,
temp2.Split(new []{Environment.NewLine},StringSplitOptions.None)
.Select(l => l.Trim()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With