How to implement string swapping in the C language?

In C language, string swapping can be achieved by using a temporary variable. The specific steps are as follows:

  1. Declare two character arrays to store the two strings that need to be swapped.
  2. Copy the first string to a temporary array using the strcpy function.
  3. Use the strcpy function to copy the second string to the position of the first string.
  4. Use the strcpy function to copy the string from the temporary array to the second string’s position.

Here is an example code:

#include <stdio.h>
#include <string.h>

int main()
{
    char str1[100], str2[100], temp[100];

    printf("输入第一个字符串: ");
    fgets(str1, sizeof(str1), stdin);

    printf("输入第二个字符串: ");
    fgets(str2, sizeof(str2), stdin);

    // 去除输入的换行符
    str1[strcspn(str1, "\n")] = '\0';
    str2[strcspn(str2, "\n")] = '\0';

    // 调换字符串
    strcpy(temp, str1);
    strcpy(str1, str2);
    strcpy(str2, temp);

    printf("调换后的第一个字符串: %s\n", str1);
    printf("调换后的第二个字符串: %s\n", str2);

    return 0;
}

After running the program, users can input two strings and the program will output the swapped result.

bannerAds