用於交換字串的 C 函式


以下是交換字串的一個示例。

示例

 即時演示

#include<stdio.h>
#include <string.h>
int main() {
   char st1[] = "My 1st string";
   char st2[] = "My 2nd string";
   char swap;
   int i = 0;
   while(st1[i] != '\0') {
      swap = st1[i];
      st1[i] = st2[i];
      st2[i] = swap;
      i++;
   }
   printf("After swapping s1 : %s
", st1);    printf("After swapping s2 : %s
", st2);    return 0; }

輸出

After swapping s1 : My 2nd string
After swapping s2 : My 1st string

在上面的程式中,聲明瞭兩個字元型別陣列 st1 和 st2,一個字元變數 ‘swap’ 和一個整數變數 i。while 迴圈用於檢查是否 st1 不為空,然後交換 st1 和 st2 的值。

char st1[] = "My 1st string";
char st2[] = "My 2nd string";
char swap;
int i = 0;
while(st1[i] != '\0') {
   swap = st1[i];
   st1[i] = st2[i];
   st2[i] = swap;
   i++;
}

更新時間: 26-06-2020

670 次瀏覽

開啟您的 事業

完成課程以獲取認證

開始
廣告
© . All rights reserved.