我正在努力学习C.我想知道是否可以将字符串的字符更改为2。这意味着如果我有一个单词:“Hello”,我如何设置一个将字符串更改为“hlelo”的函数。目前我有一个名为
的方法void word_reverse(char* str)
{
strrev(str);//changes the whole string in reverse
}
如何让它一次更改字符串中的两个字符?提前谢谢了。
答案 0 :(得分:1)
我不会在编译器前面这样做,所以你必须做的工作才能让它真正运行,但这应该让你至少开始。
char *resersi(char *string) {
char *start = string;
char *end = string;
// move the end pointer to the end (c-style strings end in '\0')
while (*end != 0) end ++;
// move the end pointer back one away from the end (we don't want to swap '\0')
end--;
// Slide the start pointer and end pointer inwards until they overlap or cross.
while (start < end) {
// Swap the values
char temp = *end;
*end = *start;
*start = temp;
// Slide the pointers
start++;
end--;
}
return string;
}
以下是您需要做的基本概要。