C语言:实现自定义strlen

strlen:计算字符串长度

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
//通过数组遍历计数
int mystrlen(char str[]) {
   
	int i = 0;
	
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个示例代码: ```c #include <stdio.h> #include <string.h> #define MAX_LEN 80 void connect(char *str1, char *str2) { int len1 = strlen(str1); int len2 = strlen(str2); if (len1 + len2 < MAX_LEN) { strcat(str1, str2); } else { printf("Error: String length exceeds the limit!\n"); } } int main() { char str1[MAX_LEN], str2[MAX_LEN]; printf("Input the first string (no more than %d characters):\n", MAX_LEN); fgets(str1, MAX_LEN, stdin); str1[strlen(str1) - 1] = '\0'; // remove the '\n' character at the end of the input printf("Input the second string (no more than %d characters):\n", MAX_LEN); fgets(str2, MAX_LEN, stdin); str2[strlen(str2) - 1] = '\0'; // remove the '\n' character at the end of the input printf("Before connection: %s\n", str1); printf("After connection: "); connect(str1, str2); printf("%s\n", str1); return 0; } ``` 在这个示例代码中,我们定义了一个名为 `connect` 的自定义函数,它接收两个字符串指针参数 `str1` 和 `str2`,并将 `str2` 连接到 `str1` 的尾部。我们使用 `strcat` 函数来实现字符串连接操作。 在主函数中,我们首先使用 `fgets` 函数从标准输入中读取两个字符串,并将它们存储在 `str1` 和 `str2` 中。然后,我们调用 `connect` 函数来连接这两个字符串,并输出连接后的结果。 请注意,我们在输入字符串时使用了 `fgets` 函数而不是 `scanf` 函数,因为 `fgets` 可以避免输入缓冲区溢出的问题。此外,我们使用 `strlen` 函数来获取字符串的长度,并在连接字符串之前检查它们的总长度是否超过了限制。如果超过了限制,我们将输出错误信息并不执行连接操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值