C //习题 7.6 写一个函数,将两个字符串连接。

本文提供两种C语言中实现字符串连接的方法:一种是使用数组和循环复制字符;另一种是使用指针和动态内存分配。每种方法都附带了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C程序设计 (第四版) 谭浩强 习题7.6

习题 7.6 写一个函数,将两个字符串连接。

IDE工具:VS2010
Note: 使用不同的IDE工具可能有部分差异。

 

代码块
方法1:使用数组
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void concatenate(char newstr[], char str1[], char str2[]){
	int len1 = strlen(str1);
	int len2 = strlen(str2);
	int k = 0;
	for(int i = 0; i < len1; i++){
		newstr[k++] = str1[i];
	}
	for(int j = 0; j < len2; j++){
		newstr[k++] = str2[j];
	}
	newstr[k] = '\0';
}

int main(){
	char str1[50], str2[50], newstr[100];
	printf("Enter string 1: ");
	gets(str1);
	printf("Enter string 2: ");
	gets(str2);
	concatenate(newstr, str1, str2);
	printf("New string: %s\n", newstr);
	
	system("pause");
    return 0;
}
方法2:使用指针、动态分配内存
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define N 50

void initialStr(char **str, int n){
	*str = (char*)malloc(n * sizeof(char));
}

void inputStr(char *str, int n){
	printf("Enter string %d: ", n);
	gets(str);
}

void concatenate(char newstr[], char str1[], char str2[]){
	int len1 = strlen(str1);
	int len2 = strlen(str2);
	int k = 0;
	for(int i = 0; i < len1; i++){
		newstr[k++] = str1[i];
	}
	for(int j = 0; j < len2; j++){
		newstr[k++] = str2[j];
	}
	newstr[k] = '\0';
}

void outputStr(char *str){
	printf("New String: %s\n", str);
}

int main(){
	char *str1 = NULL;
	char *str2 = NULL;
	char *newstr = NULL;

	initialStr(&str1, N);
	initialStr(&str2, N);
	initialStr(&newstr, N*2);

	inputStr(str1, 1);
	inputStr(str2, 2);
	concatenate(newstr, str1, str2);
	outputStr(newstr);
	
	free(str1);
	free(str2);
	free(newstr);
	
	system("pause");
    return 0;
}
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Navigator_Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值