21xrx.com
2024-09-17 03:35:58 Tuesday
登录
文章检索 我的文章 写文章
C语言中如何进行字符串交换
2023-06-15 16:25:35 深夜i     --     --
C语言 字符串交换 strncpy()函数

在C语言编程中,字符串交换是一个非常常见的操作。在实际编程中,我们可能需要交换两个字符串变量的值,以便在程序中实现对字符串的操作。本文将介绍如何在C语言中进行字符串交换。

首先,我们需要定义两个字符串变量,并初始化它们的值。然后,通过调用strncpy()函数将第一个字符串变量的值复制到一个暂存变量中,随后再将第二个字符串变量的值复制到第一个字符串变量中,并最后将暂存变量中的值复制到第二个字符串变量中。

下面是代码示例:


#include

#include

int main()

{

  char str1[20] = "hello";

  char str2[20] = "world";

  char temp[20];

  printf("Before swapping: str1 = %s, str2 = %s\n", str1, str2);

  strncpy(temp, str1, sizeof(temp));

  strncpy(str1, str2, sizeof(str1));

  strncpy(str2, temp, sizeof(str2));

  printf("After swapping: str1 = %s, str2 = %s\n", str1, str2);

  return 0;

}

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章