当前位置: 首页 > news >正文

C++ 获取 const char* 字符串长度

C++ 获取 const char* 字符串长度

获取字符串长度的方法有哪些。

strlen

strlen.c
源码如下

size_t
strlen(const char *str)
{const char *s;for (s = str; *s; ++s);return (s - str);
}

举个例子

1 2 3 4 5 6
a v b d f \0

初始化语句:s = str(只在循环开始时执行一次)
条件判断:*s(如果*s不为\0,为true
循环体:空语句;
迭代语句:++s(每次循环体执行完后执行,指针后移)
最后计算出字符串长度为5;

模板

#define HA "HA"

HA宏变量的值为字符串常量的引用,为const char(&)[3] .
所以写出如下模板函数

template <size_t N>
size_t getCharLength(const char(&arr)[N]) {std::cout << "字符串内容: " << arr << ", 字符串长度: " << N << std::endl;return N;
}

案例

#include "learn001.hpp"
#include <type_traits>template <size_t N>
size_t getCharLength(const char(&arr)[N]) {std::cout << "字符串内容: " << arr << ", 字符串长度: " << N << std::endl;return N;
}int main() {std::cout << getCharLength("Hello World!") << "\n"; const char (&str1)[6] = "Hello";const char (&str2)[6] = "Hello";const char str3[6] = "Hello";const char* str4 = new char[6]{'H','e','l','l','o','\0'};std::cout << sizeof(str1) << ", p: " << &str1 << "\n";std::cout << sizeof(str2) << ", p: " << &str2 << "\n";std::cout << sizeof(str3) << ", p: " << &str3 << "\n";std::cout << sizeof(str4) << ", p: " << reinterpret_cast<const void*>(str4) << "\n";printf("p: %p\n", str4);return 0;
}

TODO elf文件格式解析

http://www.gsyq.cn/news/32189.html

相关文章:

  • 20251027——读后感2
  • DeepSeek-DSA讲解
  • Experiment3
  • 20232403 2025-2026-1 《网络与系统攻防技术》实验三实验报告
  • CF995F Cowmpany Cowmpensation
  • WPF datagrid mvvm loaded 100M items,prism.wpf,prism.dryioc
  • LLM什么时候才能输出固定格式
  • CF708E Students Camp 题解
  • 每日反思(2025_10_27)
  • HT-083 CSP J/S题解
  • 壁纸收集
  • CF1608F MEX counting 题解
  • 【中份薯条】雷柏MT760鼠标上手改装
  • 第四篇:docker底层原理
  • 【中份薯条】雷柏MT760上手改装
  • PyPDF无限循环漏洞CVE-2025-62707技术分析
  • 题解:luogu P4948 数列求和
  • 详细介绍:论文阅读 (1) :Control Flow Management in Modern GPUs
  • 公众号排版2025年权威推荐:揭秘有一云AI编辑器为何高效?
  • 10 27
  • 同余最短路学习报告
  • 详细介绍:Redis多租户资源隔离方案:基于ACL的权限控制与管理
  • 二分查找边界
  • 学习笔记:重链剖分
  • FRP 后端无法获取请求者IP解决方案
  • 软件工程学习日志2025.10.27
  • 深入解析:TCP/IP 四层模型协作流程详解
  • Windows全版本激活教程(仅供测试)
  • 20251027周一日记
  • 10月27日