Given this example:
The ‘trim’ string will be:string text = " My testnstringrn ist quite long "; string trim = text.Trim();
“My testnstringrn ist quite long” (31 characters)Another approach is to use the String.Replace method, but that requires you to remove each individual whitespace character via multiple method calls:
The best approach is to use regular expressions. You can use the Regex.Replace method, which replaces all matches defined by a regular expression with a replacement string. In this case, use the regular expression pattern “s”, which matches any whitespace character including the space, tab, linefeed and newline.string trim = text.Replace( " ", "" ); trim = trim.Replace( "r", "" ); trim = trim.Replace( "n", "" ); trim = trim.Replace( "t", "" );
The ‘trim’ string will be:string trim = Regex.Replace( text, @"s", "" );
“Myteststringisquitelong” (23 characters)
No comments:
Post a Comment