As said in Solution1 it is not very efficient to remove characters from a string as a new string is always created as a result.
However, if you want to remove the last character of each line, you can for example use Regular Expressions.
Add this line of code into an existing method, e.g. textBox1_TextChanged or a button_Click event.
textBox1.Text = Regex.Replace(textBox1.Text, @"(?<char>\S)(?<eol>\s*$)", new MatchEvaluator(ReplaceCharWithWhiteSpace), RegexOptions.Multiline);
You might think that this line would be sufficient
textBox1.Text = Regex.Replace(textBox1.Text, @"\S$)", "", RegexOptions.Multiline);
but unfortunately the line end characters,
\r
and
\n
, are not stripped from the string, hence the need for
\s*
to include these characters. You also want to return the line ends from the replacement method, therefor I have used named groups to make it more easy.
Then add this static method to your class
private static string ReplaceCharWithWhiteSpace(Match m)
{
return m.Groups["eol"].Value;
}
This is definitely not the most efficient solution, but it works.
You can add the following fields to your class to make the execution a bit more efficient:
private static Regex lastCharExpression = new Regex(@"(?<char>\S)(?<eol>\s*$)", RegexOptions.Multiline);
private MatchEvaluator eval = new MatchEvaluator(new MatchEvaluator(ReplaceCharWithWhiteSpace));
then change to
textBox1.Text = lastCharExpression.Replace(textBox1.Text, eval);
If you want to replace only characters you can replace
\S with \w, which is equal to [a-zA-Z0-9_]