BohYoh.comトップページへ

C言語によるアルゴリズムとデータ構造

戻る  

演習8-2の解答

 ポインタxとyが指す文字列の中身をそっくり入れかえる以下の関数を作成せよ。
  void swap_str (char *x , char *y );

/* 演習8-2 二つの文字列を交換 */ #include <stdio.h> /*--- 文字列s1とs2の中身を入れかえる ---*/ void swap_str(char *x, char *y) { while (*x || *y) { char t = *x; *x++ = *y; *y++ = t; } *x = *y = '\0'; } #include <stdio.h> int main(void) { char s1[100] = "ABCD"; char s2[100] = "Z"; printf("文字列s1は\"%s\"です。\n", s1); printf("文字列s2は\"%s\"です。\n", s2); swap_str(s1, s2); puts("文字列s1とs2を交換しました。"); printf("文字列s1は\"%s\"です。\n", s1); printf("文字列s2は\"%s\"です。\n", s2); return (0); }


戻る