在C++中,我需要:
main()它,它显示原始数组与新反转的字符.我在创建实际执行倒车的功能时遇到了麻烦,因为我有一些限制:
我的函数只传入原始数组,即:
void reverse(char word[])
Run Code Online (Sandbox Code Playgroud)
编辑:到目前为止这是我的代码库:
void reverse(char word[]);
void main()
{
char word[MAX_SIZE];
cout << endl << "Enter a word : ";
cin >> word;
cout << "You entered the word " << word << endl;
reverse(word);
cout << "The word in reverse order is " << word << endl;
}
void reverse(char myword[])
{
int i, temp;
j--;
for(i=0;i<(j/2);i++)
{
temp = myword[i];
myword[i] = myword[j];
myword[j] = temp;
j--;
}
}
Run Code Online (Sandbox Code Playgroud)
尽管看起来很像家庭作业,我可以建议:
void reverse(char word[])
{
int len=strlen(word);
char temp;
for (int i=0;i<len/2;i++)
{
temp=word[i];
word[i]=word[len-i-1];
word[len-i-1]=temp;
}
}
Run Code Online (Sandbox Code Playgroud)
或者,更好的是,经典的XOR实现:
void reverse(char word[])
{
int len=strlen(word);
for (int i=0;i<len/2;i++)
{
word[i]^=word[len-i-1];
word[len-i-1]^=word[i];
word[i]^=word[len-i-1];
}
}
Run Code Online (Sandbox Code Playgroud)
Tom*_*Tom -1
如果我们谈论 C 字符串,那么你的函数应该是
void reverse(char word[],size_t wordlen)
Run Code Online (Sandbox Code Playgroud)
同一问题的第一个答案(这是Reverse a Sentence in C? 中的一个骗局? )
这并不能满足您的要求,但可以让您非常接近!
int ReverseString(char *rev)
{
if(*rev!='\0')
{
ReverseString(rev + 1);
putchar(*rev);//change this.
}
return 1;
}
Run Code Online (Sandbox Code Playgroud)
感谢@devinb。
| 归档时间: |
|
| 查看次数: |
36142 次 |
| 最近记录: |