Bloomberg LP Interview Question
Software Engineer InternsCountry: United States
How would the code change if the given input array had 2 commas on after the other:
1,,2,345,78
Yet another C approach (fully runnable).
This is pretty simple, but note the check for (t < s) may be more wasteful than simply overwriting *t with its own value. There's no harm in that, and you would avoid a conditional.
#include <stdio.h>
void remove_commas(char *s) {
char *t;
char c;
for (t = s; c = *s; ++s) {
if (c == ',') continue;
if (t < s) *t = c;
++t;
}
*t = '\0';
}
int main(int argc, char **argv) {
char arr[] = "1,234,34,54";
remove_commas(arr);
printf("%s\n", arr);
return 0;
}
#include <stdio.h>
#include <string.h>
void main(){
char s[] = "1,234,34,54";
int len=strlen(s);
int i=0;
while( *s != '\0') {
i++;
if (*s==',') memmove(s,s+1,len-i);
s++;
}
}
You will be shifting everything left. Use pointers s, d and copy s into d. Then if s == ',' increase s so that you copy some number into d.
int main() {
char str[20] = "123,45,6,7,9";
int d = 0, s = 0;
while (str[s] != '\0') if (str[s] == ',') s++; else str[d++] = str[s++];
while (str[d] != '\0') str[d++] = ' ';
cout << str << endl;
}
As we go through the string, keep count of comma and use that counter to pick the element to be overwritten.
int _tmain(int argc, _TCHAR* argv[])
{
char array[] = {"1,234,34,54"};
int iLen = strlen(array);
int comma_count = 0;
int i = 0;
while( i < iLen)
{
if(array[i] == ',')
comma_count++;
else
array[i-comma_count] = array[i];
i++;
}
array[iLen-comma_count] = 0;
}
Here is an Iterative version:
...
char szText[]="1,234,34,54";
cout << "Source text: " << szText << endl;
size_t iLen = strlen( szText );
size_t iPos = 0;
char *pszText = szText;
while( iPos < iLen )
{
if( *pszText++ != ',' )
iPos++;
else
{
strcpy( &szText[iPos], pszText );
pszText = &szText[iPos];
iLen--;
}
}
cout << "Corrected text: " << szText << endl;
...
Output:
Source text: 1,234,34,54
Corrected text: 12343454
Take a chasing pointers approach - keep a current pointer to mark position in the array, and a tail pointer such that the start of array to tail is free of commas.
- pacman March 20, 2013