どうも、ちょげ(@chogetarou)です。
文字列(string)を反転して逆順にする方法を紹介します。
方法
文字列(string)を反転して逆順にするには、ループを使います。
まず、初期値「0」と初期値「文字列の末尾のインデックス」の2つのループ変数を用意します。
ループ条件に、初期値「0」のループ変数が文字列の半分の長さ未満を指定します。
ループ後の処理には、初期値「0」のループ変数を「+1」、初期値「文字列の末尾のインデックス」のループ変数を「-1」します。
そして、ループ処理で、文字列の2つのループ変数のインデックスの要素を入れ替えます。
//text=対象の文字列
int count = strlen(text);
for (int i = 0, j = count - 1; i < count / 2; ++i, --j) {
//要素の入れ替え
char temp = text[i];
text[i] = text[j];
text[j] = temp;
}
上記のループは、文字列を反転して逆順にします。
使用例
#include <stdio.h>
#include <string.h>
int main(void){
char text[] = "Hello,World";
int count = strlen(text);
for (int i = 0, j = count - 1; i < count / 2; ++i, --j) {
char temp = text[i];
text[i] = text[j];
text[j] = temp;
}
printf("%s", text);
return 0;
}
出力:
dlroW,olleH
コメント