我在接受采访时被问到这个问题
我原本应该在自己的位置反转字符数组而不是反转整个字符数组.
如果
char *ch="krishna is the best";
Run Code Online (Sandbox Code Playgroud)
然后我应该以这样的方式反转,输出应该是这样的
anhsirk si eht tseb
Run Code Online (Sandbox Code Playgroud)
我无法在面试中编写代码.任何人都建议我如何写这样做.
可以在指针的帮助下完成吗?
如果面试官没有告诉我将其反转到自己的位置,那么如果使用另一个数组字符数组很容易处理,那么在反转它之后会有新的字符串吗?
你的面试官都不能为此编写代码.
char *ch="krishna is the best";
Run Code Online (Sandbox Code Playgroud)
你不能改变只读内存部分的数据,并ch指向只读内存.
更新: - 摘录自N1548(§6.7.9)
例8
声明
char s[] = "abc", t[3] = "abc";
定义了''plain''char数组对象s和t,其元素用字符串文字初始化.
此声明与
char s[] = { 'a', 'b', 'c', '\0' },t[] = { 'a', 'b', 'c' };
数组的内容相同.
另一方面,声明
char *p = "abc";
用类型定义p‘‘pointer to char’’并将其初始化为指向‘‘array of char’’具有长度为4的类型的对象,其元素用字符串文字初始化.如果尝试使用p修改数组的内容,则行为未定义.
您可以看到应用交换此类数据类型是危险的.
建议将代码编写为: -
char ch[]="krishna is the best";
然后在每次遇到空格字符时应用XOR交换.
char *ch="krishna is the best";
Run Code Online (Sandbox Code Playgroud)
没办法,这是一个指向只读字符串文字的指针。让我们想象一下,你的面试官了解 C 并且写了这样的内容:
char str[]="krishna is the best";
Run Code Online (Sandbox Code Playgroud)
然后你可以做这样的事情:
#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 != '\0') /* 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 != '\0');
}
int main (void)
{
char str[]="krishna is the best";
str_reverse_sentence (str);
puts(str);
}
Run Code Online (Sandbox Code Playgroud)