C++ string 字符串 结尾 标志 \0

看个示例

#include<iostream>
#include<string>
using namespace std;
 
int main()
{
	string str = "hello";
	str[3] = '\0';
	cout << str << endl;
	return 0;	
} 
输出:hel o

应该明白了点什么!在C++中\0不能作为识别string类字符串的结尾
其实C++string类也不需要识别结尾,因为你需要用到的C++的函数库基本都帮你解决了

再看个例子

#include<iostream>
#include<string>
using namespace std;
 
int main()
{
	string str = "hello";
	int i = 0,len = 0;
	while(str[i++])
	{
		++len;
	}
	cout << "len = " << len << endl;
	cout << "str.length() = " << str.length() << endl;
	return 0;	
} 
输出:
len = 5
str.length() = 5

两个值len和str.length()相等,说明len的计算值是对的,也就是说string类结尾处还是有\0的。说明一下我用的dev编译运行的。至于\0 这是编译器产商加进去的(根据具体实现而言,有的编译器就没加),并非C++本身所要求的,C++并没有要求string类要有结尾

原文链接: https://www.cnblogs.com/lixuejian/p/13153294.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    " loading="lazy" src="https://www.ccppcoding.com/wp-content/uploads/2023020407005197.bmp"/>C++ string 字符串 结尾 标志 <img decoding=" loading="lazy" class="j-lazy" src="https://www.ccppcoding.com/wp-content/themes/justnews/themer/assets/images/lazy.png" data-original="https://www.ccppcoding.com/wp-content/uploads/2023020407005197.bmp"/>

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/199034

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月12日 下午8:01
下一篇 2023年2月12日 下午8:01

相关推荐