6-5 D字符串的连接函数 (6分)

pta,c,浙大
D字符串是动态分配内存的字符串,它也采用char数组来保存字符串中的字符,但是这个数组是在堆中动态分配得到的。

本题要求编写D字符串的连接函数。

函数接口定义:

char *dstr_add(char *s, char c);
char *dstr_concat(char *this, const char *that);

dstr_add在s的后面加上一个字符c,返回新的字符串。 dstr_concat在this后面加上字符串that,返回新的字符串。 这两个函数的第一个参数都必须是D字符串,不能是静态数组。

裁判测试程序样例:

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

//	这两个函数由系统提供
char *dstr_readword();
char *dstr_create(
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
下面是6个常见的字符串处理函数C语言代码实现: 1. 字符串长度计算函数 ```c #include <stdio.h> #include <string.h> int str_len(char *str) { int len = 0; while (*str != '\0') { len++; str++; } return len; } int main() { char str[] = "hello world"; printf("Length of the string is %d\n", str_len(str)); return 0; } ``` 2. 字符串复制函数 ```c #include <stdio.h> #include <string.h> void str_cpy(char *dest, char *src) { while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } int main() { char src[] = "hello world"; char dest[20]; str_cpy(dest, src); printf("Copied string is %s\n", dest); return 0; } ``` 3. 字符串连接函数 ```c #include <stdio.h> #include <string.h> void str_cat(char *dest, char *src) { while (*dest != '\0') { dest++; } while (*src != '\0') { *dest = *src; dest++; src++; } *dest = '\0'; } int main() { char str1[20] = "hello"; char str2[] = "world"; str_cat(str1, str2); printf("Concatenated string is %s\n", str1); return 0; } ``` 4. 字符串比较函数 ```c #include <stdio.h> #include <string.h> int str_cmp(char *str1, char *str2) { while (*str1 == *str2) { if (*str1 == '\0' || *str2 == '\0') { break; } str1++; str2++; } if (*str1 == '\0' && *str2 == '\0') { return 0; } else { return -1; } } int main() { char str1[] = "hello"; char str2[] = "world"; int result = str_cmp(str1, str2); if (result == 0) { printf("Strings are equal\n"); } else { printf("Strings are not equal\n"); } return 0; } ``` 5. 字符串查找函数 ```c #include <stdio.h> #include <string.h> char *str_find(char *str, char c) { while (*str != '\0') { if (*str == c) { return str; } str++; } return NULL; } int main() { char str[] = "hello world"; char c = 'o'; char *result = str_find(str, c); if (result == NULL) { printf("Character not found\n"); } else { printf("Character found at position %ld\n", result - str); } return 0; } ``` 6. 字符串反转函数 ```c #include <stdio.h> #include <string.h> void str_reverse(char *str) { int len = strlen(str); for (int i = 0; i < len / 2; i++) { char temp = str[i]; str[i] = str[len - i - 1]; str[len - i - 1] = temp; } } int main() { char str[] = "hello world"; str_reverse(str); printf("Reversed string is %s\n", str); return 0; } ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值