【c语言】链接字符串

输入两个字符串s和t,将字符串s连接到字符串t的尾部,再输出字符串t。要求定义和调用strc(s,t)完成字符串的连接。

#include <stdio.h>
void strc(char *s, char *t);
int main(void)
{
	char s[80], t[80];
	printf("Enter s: ");
	gets(s);
	printf("Enter t: ");
	gets(t);
	strc(s, t);
	puts(t);      
	return 0;
}
void strc(char *s, char *t)
{ 
	while (*t != '\0'){
		t++;    
    }
	while ((*t =*s) != '\0'){
		t++;
		s++;
	}
}

本题主要练习自定义函数和指针的使用。

应注意指针的移动和自定义函数的形参形式。

输出参考:

 

 

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
如果需要连接多个字符串,可以设计一个自定义的连接字符串函数。以下是一个简单的C语言连接字符串函数的设计: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> char* string_concat(int count, ...) { va_list args; int total_length = 0; char *result, *temp; // 计算所有字符串的总长度 va_start(args, count); for (int i = 0; i < count; i++) { total_length += strlen(va_arg(args, char*)); } va_end(args); // 分配空间 result = (char*) malloc(total_length + 1); result[0] = '\0'; // 连接字符串 va_start(args, count); for (int i = 0; i < count; i++) { temp = va_arg(args, char*); strcat(result, temp); } va_end(args); return result; } ``` 该函数使用了可变参数列表来接收任意数量的字符串,将它们连接成一个新的字符串。具体来说,该函数的实现包括以下步骤: 1. 首先,使用va_list和va_start宏定义一个可变参数列表args,并遍历所有参数,计算所有字符串的总长度。 2. 然后,使用malloc函数为结果字符串分配足够的空间。注意,这里需要预留一个字节来存储字符串结束符'\0'。 3. 接下来,使用va_start宏重新遍历所有参数,将它们依次连接到结果字符串中。 4. 最后,返回连接后的字符串使用该函数的示例代码如下: ```c #include <stdio.h> int main() { char *result = string_concat(3, "Hello, ", "world!", " How are you?"); printf("%s\n", result); free(result); return 0; } ``` 输出结果为: ``` Hello, world! How are you? ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值