Trim char array

Background: I was invited to an interview with a high profile company, and I was asked the following question before I was told that I had not been interviewed for this post (C #, mvc3, razor). I am sincerely interested in how to solve this problem.

Question: "Write a method that takes a char array, trims whitespace, and returns the same array." After some thought, I was told to replace the space 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 that I should use the same array, I can not put it in a list and call ToArray() . However, I think that if the array remains the same size, it cannot be "trimmed".

+4
source share
5 answers

Assuming they mean replacing whitespace with null characters, the solution is simple:

Step 1: From the beginning of the line (represented as an array of characters), replace the whitespace until a non-WS character is encountered.

Step 2: From the end of the line running back, do the same.

 public static void Trim(Char[] str) { int maxI = 0; // an optimisaiton so it doesn't iterate through chars already encountered for(int i=0;i<str.Length;i++) { if( Char.IsWhitespace( str[i] ) ) str[i] = '\0'; else { maxI = i; break }; } for(int i=str.Length-1;i>maxI;i--) { if( Char.IsWhitespace( str[i] ) ) str[i] = '\0'; } } 
+2
source

Perhaps they meant \ 0 (the NUL character), not dash-0

+5
source
 public static char[] Trim(char[] str) { return str.Where(x => !Char.IsWhiteSpace(x)).ToArray(); } 
+1
source

This is ugly and untested, but it all happens 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'; } 
0
source

I assume that you were asked to remove the empty space between the line and then fill the char array for the rest of the elements of the array with '\ 0'

eg. "Convert this string" to "Convertthisstring" and fill in the remaining array 2 '\ 0'

Decision:

  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; } 
0
source

All Articles