Trim a char array
arrays, c#
Solution
Assuming they meant to replace whitespace characters with null characters then the solution is simple:
Step 1: From the start of the string (represented as a character array) replace whitespace characters until a non-WS character is encountered.
Step 2: From the end of the string, working backwards, do the same.
public static void Trim( Char[] chars )
{
int maxIdx = 0; // an optimization so it doesn't iterate through chars already encountered
for( int i = 0;i < chars.Length; i++ )
{
if( Char.IsWhitespace( chars[i] ) )
{
chars[i] = '\0';
}
else
{
maxIdx = i;
break;
}
}
for( int i = chars.Length - 1; i > maxIdx; i-- )
{
if( Char.IsWhitespace( chars[i] ) ) chars[i] = '\0';
}
}
Problem
Background: I was invited to an interview at a high profile company and I was asked the following question before being told I failed the interview for the position (C#,mvc3,razor). I'm genuinely interested in how to solve this. Question: `"Write a method that takes a char array, trims whitespace, and returns the same array."` After some thinking I was told to replace the whitespace with "\o". I started with: ``` public static char[] Trim(char[] c) { for (int i = 0; i < c.Length; i++) { if (c[i] == '\r' || c[i] == '\n' || c[i] == '\t') { c[i] = '\o'; } } } ``` I was told I have to use the same array, can't put it in a list and call `ToArray()`. However I think if the array stays the same size it is impossible to "trim it".