C文字列を反転します
この簡単な記事では、nullで終了する('\0'
)連続する文字シーケンスのブロック。
標準的な解決策は、ループを使用して指定されたC文字列の前半をループし、現在の文字をC文字列の残りの半分の対応する文字と交換することです。これは次の方法で実行できます。
1.単純なforループを使用する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
#include <stdio.h> #include <string.h> //ポインタ演算を使用せずにC文字列を反転する関数 void reverse(char* str) { //文字列の長さを取得します int n = strlen(str); //文字列の両端から文字の交換を開始します for (int i = 0, j = n - 1; i < j; i++, j--) { char ch = str[i]; str[i] = str[j]; str[j] = ch; } } int main(void) { char str[] = "Reverse me"; reverse(str); printf("%s", str); return 0; } |
2.ポインタ演算の使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <stdio.h> #include <string.h> //ポインタ演算を使用してC文字列を反転する関数 void reverse(char* str) { // `str`がNULLの場合、何もしません if (str == NULL) { return; } //文字列の最後の文字の終わりへのポインタを取得します char* end_ptr = str + (strlen(str) - 1); //文字列の両端から文字の交換を開始します while (end_ptr > str) { char ch = *str; *str = *end_ptr; *end_ptr = ch; // strをインクリメントし、end_ptrをデクリメントします ++str, --end_ptr; } } int main(void) { char str[] = "Reverse me"; reverse(str); printf("%s", str); return 0; } |
3.XOR演算子を使用する
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
#include <stdio.h> #include <string.h> //XOR演算子を使用してC文字列を反転する関数 void reverse(char* str) { // `str`がNULLの場合、何もしません if (str == NULL) { return; } //`str`の最後の文字の終わりへのポインタを取得します char* end_ptr = str + (strlen(str) - 1); //文字列の両端から文字の交換を開始します。 // XORが失敗するため、`str`は`end_ptr`よりも厳密に小さくする必要があります //両方が同じメモリ位置を参照している場合 while (str <= end_ptr) { //両方のポインタが指す値を交換します *str = *str ^ *end_ptr; *end_ptr = *str ^ *end_ptr; *str = *str ^ *end_ptr; // strをインクリメントし、end_ptrをデクリメントします ++str, --end_ptr; } } int main(void) { char str[] = "Reverse me"; reverse(str); printf("%s", str); return 0; } |
これで、Cストリングを逆にすることができます。