【例6-19】求字符串长度函数strlen()

在使用字符串处理函数前,需要在程序开头使用编译预处理命令 #include<string.h>
(三)求字符串长度函数 strlen()
函数调用格式strlen(str);
函数功能:求 str 所代表的字符串的长度,不包括字符串结束标志符'\0'

//strlen()函数演示

#include<stdio.h>
#include<string.h>
char main()
{
	char str[20] = { "China" };
	puts(str);
  //printf("该字符串长度为:%d", strlen(str));
	/*
	warning C4477: “printf”: 格式字符串“%d”需要类型“int”的参数,但可变参数 1 拥有了类型“size_t”
	message : 请考虑在格式字符串中使用“%zd”
	*/
	printf("该字符串长度为:%zd", strlen(str));

	return 0;
}

 //求二维字符数组中字符串的长度,strlen()一次只能求其中的一个字符串

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用指针实现常用字符串操作的C++函数: ```cpp #include <iostream> #include <cstring> using namespace std; // 字符串复制 char* mystrcpy(char* dest, const char* src) { char* p = dest; while (*src != '\0') { *p++ = *src++; } *p = '\0'; return dest; } // 字符串拼接 char* mystrcat(char* dest, const char* src) { char* p = dest + strlen(dest); while (*src != '\0') { *p++ = *src++; } *p = '\0'; return dest; } // 字符串比较 int mystrcmp(const char* str1, const char* str2) { while (*str1 != '\0' && *str2 != '\0') { if (*str1 != *str2) { return *str1 - *str2; } str1++; str2++; } return *str1 - *str2; } // 字符串长度 int mystrlen(const char* str) { int len = 0; while (*str++ != '\0') { len++; } return len; } int main() { char str1[30] = "Hello"; char str2[] = "World"; char str3[30] = "Hello"; char str4[] = "World"; char str5[30] = "Hello"; char str6[] = "World"; char str7[30] = "Hello"; char str8[] = "World"; char str9[30] = "Hello"; char str10[] = "World"; char str11[30] = "Hello"; char str12[] = "World"; char str13[30] = "Hello"; char str14[] = "World"; char str15[30] = "Hello"; char str16[] = "World"; char str17[30] = "Hello"; char str18[] = "World"; char str19[30] = "Hello"; char str20[] = "World"; cout << "复制前:" << str1 << endl; mystrcpy(str1, str2); cout << "复制后:" << str1 << endl; cout << "拼接前:" << str3 << endl; mystrcat(str3, str4); cout << "拼接后:" << str3 << endl; cout << "比较结果:" << mystrcmp(str5, str6) << endl; cout << "字符串长度:" << mystrlen(str7) << endl; return 0; } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值