Reputation: 20004
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".
Upvotes: 5
Views: 9497
Reputation: 155145
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';
}
}
Upvotes: 3
Reputation: 1
I guess what you might have been asked is to remove white space from between the string and then fill the char array for the remaining elements of the array with '\0'
e.g. "Convert this string" to "Convertthisstring" and fill the remaining array with 2 '\0'
Solution:
char[] TrimWhiteSpace(char[] source)
{
int i, j = 0;
for (i = 0; i < source.Length; i++)
{
if (!char.IsWhiteSpace(source[i]))
{
source[j] = source[i];
j++;
}
}
for (int x = 0; x < (i - j); x++)
{
source[j + x] = '\0';
}
return source;
}
Upvotes: 0
Reputation: 51156
This is ugly and untested, but it does the whole thing in a single pass without creating a new array:
public static void Trim(Char[] str) {
int nonNullIndex = 0;
int lastNonNullIndex = 0;
for(int i=0;i<str.Length;i++) {
str[nonNullIndex] = str[i];
if( !Char.IsWhitespace( str[i] ) || nonNullIndex > 0) nonNullIndex++;
if( !Char.IsWhitespace( str[i] )) lastNonNullIndex = i;
}
nonNullIndex++
str[lastNonNullIndex] = '\0';
}
Upvotes: 0
Reputation: 5603
public static char[] Trim(char[] str)
{
return str.Where(x => !Char.IsWhiteSpace(x)).ToArray();
}
Upvotes: 2
Reputation: 1806
They may have meant \0 (NUL character), not dash-0
Upvotes: 6