Wednesday, April 16, 2008

How to remove leading and trailing characters from string in csharp (c#).

To remove leading and trailing characters from string in csharp (c#) we can use methods String.Trim(), String.TrimEnd() or String.TrimStart().

Samples:

originalLine = " message with space, ";
actualLine = originalLine.Trim();
DisplayMessage(originalLine, actualLine);


trimOutput1



originalLine = " message with space, ";
actualLine = originalLine.TrimEnd();
DisplayMessage(originalLine, actualLine);



trimOutput2



originalLine = " message with space, ";
actualLine = originalLine.TrimStart();
DisplayMessage(originalLine, actualLine);



trimOutput3



originalLine = " message with space, ";
actualLine = originalLine.Trim(new char[] { ' ', ',' });
DisplayMessage(originalLine, actualLine);


trimOutput4



Sometimes interesting to see implementation of C# methods.



So, let's see method String.Trim(Char[]):



// Removes a string of characters from the ends of this string. 
public String Trim(params char[] trimChars) {
if (null==trimChars || trimChars.Length == 0) {
trimChars=WhitespaceChars;
}
return TrimHelper(trimChars,TrimBoth);
}


and basic method TrimHelper():



private String TrimHelper(char[] trimChars, int trimType) { 
//end will point to the first non-trimmed character on the right
//start will point to the first non-trimmed character on the Left
int end = this.Length-1;
int start=0;

//Trim specified characters.
if (trimType !=TrimTail) {
for (start=0; start < this.Length; start++) {
int i = 0;
char ch = this[start];
for( i = 0; i < trimChars.Length; i++) {
if( trimChars[i] == ch) break;
}
if( i == trimChars.Length) { // the character is not white space
break;
}
}
}

if (trimType !=TrimHead) {
for (end= Length -1; end >= start; end--) {
int i = 0;
char ch = this[end];
for(i = 0; i < trimChars.Length; i++) {
if( trimChars[i] == ch) break;
}
if( i == trimChars.Length) { // the character is not white space
break;
}
}
}

//Create a new STRINGREF and initialize it from the range determined above.
int len = end -start + 1;
if (len == this.Length) {
// Don't allocate a new string is the trimmed string has not changed.
return this;
}
else {
if( len == 0) {
return String.Empty;
}
return InternalSubString(start, len, false);
}
}





References:



String.Trim Method

1 comment:

Anonymous said...

For anyone interested in speed, this blog posting benchmarks the fastest way to Trim() strings:
http://cc.davelozinski.com/c-sharp/fastest-way-to-trim-strings
using multiple techniques.