[英]Reversing a word : C++
我想在C ++中反轉一個char字符串。 我寫了這段代碼:
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80];
int i, j;
int l;
l = strlen(word);
for(i = 0, j = l; i < l-1; i++, j--){
word[j] = rev[i];
}
cout << rev << endl;
return 0;
}
在終端中,它顯示了一些這樣的字符:
83???uH??? ... Something like this
您的字符數組rev不是零終止的。
而且,您不是在寫版本,而是在寫單詞。:)
word[j] = rev[i];
由於條件,循環也是錯誤的
i < l-1;
必須有
i < l;
該程序可以如下所示
#include <iostream>
#include <cstring>
int main()
{
char word[80] = "polymorphism";
char rev[80];
size_t n = std::strlen( word );
size_t i = 0;
for ( ; i < n; i++ ) rev[i] = word[n - i - 1];
rev[i] = '\0';
std::cout << word << std::endl;
std::cout << rev << std::endl;
return 0;
}
程序輸出為
polymorphism
msihpromylop
考慮到您可以使用標頭<algorithm>
聲明的標准算法std::reverse_copy
進行相同的操作。 例如
#include <iostream>
#include <cstring>
#include <algorithm>
int main()
{
char word[80] = "polymorphism";
char rev[80];
size_t n = std::strlen( word );
*std::reverse_copy( word, word + n, rev ) = '\0';
std::cout << word << std::endl;
std::cout << rev << std::endl;
return 0;
}
程序輸出與上面相同
polymorphism
msihpromylop
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80] = {'\0'};
int i = 0;
int last = strlen(word) - 1;
while(last >= 0) {
rev[i] = word[last];
i++;
last--;
}
cout << rev << endl;
return 0;
}
我對您的代碼進行了3處更改:
更改1:由於字符串長度為l
,因此索引從0
到l-1
。
變更2: rev
將存儲word
的值,而不是相反。
更改3:正確的字符串應以\\0
終止。
#include <iostream>
#include <string.h>
using namespace std;
int main(){
char word[80] = "polymorphism";
char rev[80]="";
int i, j;
int l;
l = strlen(word);
for(i = 0, j = l-1; i < l; i++, j--){ //change 1
rev[i] = word[j]; // change 2
}
rev[i]='\0'; // change 3
cout<<rev;
return 0;
}
可用的ideone鏈接: http ://ideone.com/kIqeNF
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.