在一次采访中问了我这个问题
我应该在自己的位置反转字符数组,而不是反转整个字符数组。
如果
char *ch="krishna is the best";
然后我应该以这样一种方式反转,输出应该像一样
anhsirk si eht tseb
我无法在面试中编写代码。有人能建议我如何编写代码吗。?
这能在指针的帮助下完成吗?
如果面试官没有告诉我将其反转到自己的位置,那么使用数组中的另一个字符数组会很容易吗?
你的面试官都不能为此编写代码
char *ch="krishna is the best";
您无法更改只读内存中的数据,并且ch
指向只读内存。
更新:-N1548(§6.7.9)摘录
示例8
声明char s[] = "abc", t[3] = "abc";
定义"plain"字符数组对象s和t,它们的元素是用字符串文字初始化的
此声明与
相同char s[] = { 'a', 'b', 'c', ' ' },
t[] = { 'a', 'b', 'c' };
数组的内容是可修改的
另一方面,声明char *p = "abc";
使用类型‘‘pointer to char’’
定义p,并将其初始化为指向类型‘‘array of char’’
的对象长度为4,其元素用字符串文字初始化。如果尝试使用p
修改数组的内容,行为未定义。
您可以看到在这种数据类型上应用交换是危险的。
建议将代码写为:-
char ch[]="krishna is the best";
然后在每次遇到空间字符时应用XOR交换。
如果我理解得当,这听起来并不太难。伪码:
let p = ch
while *p != ' '
while *p is whitespace
++p
let q = last word character starting from p
reverse the bytes between p and q
let p = q + 1
一旦有了指向开始和结束的指针,字节范围的反转就变得微不足道了。只需循环一半的距离,然后交换字节。
当然,正如其他地方所指出的,我假设ch
中的缓冲区实际上是可修改的,这需要对您显示的代码进行更改。
char *ch="krishna is the best";
不行,这是一个指向只读字符串文字的指针。让我们想象一下,你的面试官认识C,并写下了以下内容:
char str[]="krishna is the best";
然后你可以做这样的事情:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char* str_reverse_word (char* str)
{
char* begin;
char* end;
char* the_end;
char tmp;
while(isspace(*str)) /* remove leading spaces from the string*/
{
str++;
}
begin = str;
end = str;
while(!isspace(*end) && *end != ' ') /* find the end of the sub string */
{
end++;
}
the_end = end; /* save this location and return it later */
end--; /* move back 1 step to point at the last valid character */
while(begin < end)
{
tmp = *begin;
*begin = *end;
*end = tmp;
begin++;
end--;
}
return the_end;
}
void str_reverse_sentence (char* str)
{
do
{
str = str_reverse_word(str);
} while (*str != ' ');
}
int main (void)
{
char str[]="krishna is the best";
str_reverse_sentence (str);
puts(str);
}
您可以逐字颠倒。
只需读取该字符串直到' '(space)
,即您将获得krishna
并反转该字符串,然后继续读取原始字符串直到另一个' '(space)
并继续反转该字符串。
字符串真的必须在适当的位置反转吗,还是只是输出需要反转?
如果是前者,那么你就有问题了。如果申报真的是
char *ch = "krishna is the best";
然后您正试图修改字符串文字,而尝试修改字符串文字时的行为是未定义的。如果您在一个字符串文本存储在只读内存中的平台上工作,则会出现运行时错误。您要么需要将申报更改为
char ch[] = "krishna is the best";
或者分配一个动态缓冲区并将字符串的内容复制到
char *ch = "krishna is the best";
char *buf = malloc(strlen(ch) + 1);
if (buf)
{
strcpy(buf, ch);
// reverse the contents of buf
}
以便在适当的位置实现反转。
如果只需要反转输出,那么存储并不重要,只需要几个指针来跟踪每个子字符串的开头和结尾。例如:
#include <stdio.h>
#include <string.h>
int main(void)
{
char *ch = "krishna is the best";
char *start, *end;
// point to the beginning of the string
start = ch;
// find the next space in the string
end = strchr(start, ' ');
// while there are more spaces in the string
while (end != NULL)
{
// set up a temporary pointer, starting at the space following the
// current word
char *p = end;
// while aren't at the beginning of the current word, decrement the
// pointer and print the character it points to
while (p-- != start)
putchar(*p);
putchar(' ');
// find the next space character, starting at the character
// following the previous space character.
start = end + 1;
end = strchr(start, ' ');
}
// We didn't find another space character, meaning we're at the start of
// the last word in the string. We find the end by adding the length of the
// last word to the start pointer.
end = start + strlen(start);
// Work our way back to the start of the word, printing
// each character.
while (end-- != start)
putchar(*end);
putchar('n');
fflush(stdout);
return 0;
}
也许有更好的方法可以做到这一点,这只是我的想法。
目前还不确定具体的代码,但以下是我的操作方法(假设您能够重写原始变量)。
1) 使用空格作为分隔符将字符串拆分为单词数组
2) 循环遍历数组并按的相反顺序对单词进行排序
3) 重新生成字符串并将其赋值回变量。
这里有一个使用XOR:的就地交换
void reverseStr(char *string)
{
char *start = string;
char *end = string + strlen(string) - 1;
while (end > start) {
if (*start != *end)
{
*start = *start ^ *end;
*end = *start ^ *end;
*start = *start ^ *end;
}
start++;
end--;
}
}
当然,这是假设string
在可写内存中,所以不要抱怨它不是。
如果你需要先把单词分开,给我几分钟时间,我会写一些东西。
编辑:
对于用空格分隔的单词(0x20
),以下代码应该有效:
void reverseStr(char *string)
{
// pointer to start of word
char *wordStart = string;
// pointer to end of word
char *wordEnd = NULL;
// whether we should stop or not
char stop = 0;
while (!stop)
{
// find the end of the first word
wordEnd = strchr(wordStart, ' ');
if (wordEnd == NULL)
{
// if we didn't a word, then search for the end of the string, then stop after this iteration
wordEnd = strchr(wordStart, ' ');
stop = 1; // last word in string
}
// in place XOR swap
char *start = wordStart;
char *end = wordEnd - 1; // -1 for the space
while (end > start) {
if (*start != *end)
{
*start = *start ^ *end;
*end = *start ^ *end;
*start = *start ^ *end;
}
start++;
end--;
}
wordStart = wordEnd + 1; // +1 for the space
}
}
Here is my working solution ->
#include<stdio.h>
#include<ctype.h>
#include<string.h>
char * reverse(char *begin, char *end)
{
char temp;
while (begin < end)
{
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
/*Function to reverse words*/
char * reverseWords(char *s)
{
char *word_begin = s;
char *temp = s; /* temp is for word boundry */
while( *temp )
{
temp++;
if (*temp == ' ')
{
reverse(word_begin, temp-1);
}
else if(*temp == ' ')
{
reverse(word_begin, temp-1);
word_begin = temp+1;
}
} /* End of while */
return s;
}
int main(void)
{
char str[]="This is the test";
printf("nOriginal String is -> %s",str);
printf("nReverse Words t -> %s",reverseWords(str));
return 0;
}
Here is my working solution ->
#include<stdio.h>
#include<ctype.h>
#include<string.h>
char * reverse(char *begin, char *end)
{
char temp;
while (begin < end)
{
temp = *begin;
*begin++ = *end;
*end-- = temp;
}
}
/*Function to reverse words*/
char * reverseWords(char *s)
{
char *word_begin = s;
char *temp = s; /* temp is for word boundry */
while( *temp )
{
temp++;
if (*temp == ' ')
{
reverse(word_begin, temp-1);
}
else if(*temp == ' ')
{
reverse(word_begin, temp-1);
word_begin = temp+1;
}
} /* End of while */
return s;
}
int main(void)
{
char str[]="This is the test";
printf("nOriginal String is -> %s",str);
printf("nReverse Words t -> %s",reverseWords(str));
return 0;
}