The relationship between String, Array and Character is a very important subject in any Firmware interview. Here are some common questions and example solution.
Copy string A to string B (consider A and B might overlap)
char* copy(char *d, char *s)
{
int n = strlen(s);
char *ret = d;
if ((d - s) >= 0) {
d += n;
s += n;
for ( ; n >= 0; n--)
*d-- = *s--;
}
else
while (*d++ = *s++);
return ret;
}
Reverse a sentense: Ex."I am a real boy!" to "boy! real a am I"
void reverse_string(char *str)
{
if (!str)
return;
int n = strlen(str);
char *c, *tmp;
c = str;
reverse(str, str + n - 1);
while (1) {
for (; *c == ' ' && *c != '\0'; c++);
if (*c == '\0')
return;
tmp = c;
for (; *c != ' ' && *c != '\0'; c++);
reverse(tmp, c - 1);
if (*c == '\0')
return;
}
}
void reverse(char *c1, char *c2)
{
while (c2 > c1) { // It is simply to reverse a string char tmp = *c1; // ex. 'A string' -> 'gnirts A'
*c1++ = *c2;
*c2-- = tmp;
}
}
Remove Duplicate Characters in a string: Ex."hiiii!Iammmbackkkk" to "hi!Iamback"
void remove_dup(char *str)
{
char pre_c = str[0] + 1;
with str[0]. The same as *str + 1;
char *c1, *c2;
for (c1 = c2 = str; *c2 != '\0'; ) {
if (*c2 == pre_c) {
c2++; // use c2 to compare contiguous chars
} // If the same, skip it by adding 1 else {
pre_c = *c2; // If not the same,
*c1++ = *c2++; // put the char into string c1.
} } *c1 = '\0'; // the end of the string}
沒有留言:
張貼留言