以下是使用C语言拼接两个字符串的示例代码,该代码允许用户从键盘输入两个字符串,并使用strcat()函数将它们连接在一起。

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

int main()
{
    char str1[50], str2[50];
    printf('Enter the first string: ');
    fgets(str1, 50, stdin);
    printf('Enter the second string: ');
    fgets(str2, 50, stdin);

    // Remove newline character from the end of the first string
    str1[strcspn(str1, '\n')] = 0;

    // Calculate the length of the first string
    int len1 = strlen(str1);

    // Concatenate the second string to the end of the first string
    strcat(str1, str2);

    printf('The concatenated string is: %s\n', str1);

    return 0;
}

代码说明:

  1. 使用fgets()函数从键盘输入两个字符串,并存储在str1str2数组中。
  2. 使用strcspn()函数找到第一个字符串中第一个换行符的位置,并将其替换为0,从而去除换行符。
  3. 使用strlen()函数计算第一个字符串的长度,存储在len1变量中。
  4. 使用strcat()函数将第二个字符串连接到第一个字符串的末尾,结果存储在str1数组中。
  5. 最后,使用printf()函数输出拼接后的字符串。

本示例演示了C语言中字符串处理的常见操作,包括键盘输入、去除换行符、计算字符串长度以及字符串拼接。

C语言字符串拼接:键盘输入并连接两个字符串

原文地址: https://www.cveoy.top/t/topic/m6JW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录