首先确实得承认,这么久才知道strlen()函数只能对char类型指针起作用,并且不读取’\0’;
这样一来其实就展现出了strlen()的用法和它与sizeof()的区别,下面来看实例操作。
1.char类型数组
#include <iostream>
#include <string.h>
using namespace std;
int main()
{ char ch1[] = "I am LiHua";
cout << "ch1数组的长度为:" << strlen(ch1) << endl;
cout << "ch1数组的实际长度为:" << sizeof(ch1) << endl;
//结果为:
//ch1数组的长度为:10
//ch1数组的实际长度为:11
}
很明显,在size of()函数中,它将数组结束标志’\0’看做是占一个字节空间的值;而strlen()到’\0’结束读取,是不太亲民的,也就是有要求的。
2. 下面我们接着来看
#include <iostream>
#include <string.h>
using namespace std;
int main()
{ string str1 = "I am LiHua";
cout << "str1的长度为:" << strlen(str1) << endl;
//上述语句就会报错,因为str1并不是指针类型
cout << "str1的实际长度为:"<< sizeof(str1) << endl;
//上述输出结果为:
//str1的实际长度为:不确定值,不建议使用
}
3.在纯指针运用时,如下
#include <iostream>
#include <string.h>
using namespace std;
int main()
{ char * str = "I am always LiHua";
cout << "str指向的内容的长度为:" << strlen(str) <<endl;
cout << "str本身的长度为:" << sizeof(str) << endl;
//输出结果为:
//str指向的内容的长度为:17
//str本身的长度为:4
//指针的长度永远是4
}
4.下面在类中运用这一特性
/*
*main()函数
*/
#include <iostream>
#include "MyString.h"
using namespace std;
void TestStr();
int main()
{
}
void Teststr()
{ String str("I am LiHua");
cout << str << endl;
cout << strlen(str.m_value) << endl;
//输出结果应该为
//I am LiHua
//I am LiHua
//10
/*
*Mystring.h
*/
#include <iostream>
using namespace std;
class String:
{ public:
String();//无参构造函数
String(char *);
~String();//析构函数
friend ostream & operator<<(ostream &, String &);
private:
int m_length;
char * m_value;
/*
*MyString.cpp
*/
#include <iostream>
#include "MyString.h"
String::String():m_length(0)
{ this->m_value = new char[m_length + 1];
this->m_value[0] = '\0';
}
String::String(char * str)
{ //将str中m_value指向的内容赋给this->m_value
m_length = strlen(str.m_value);
m_value = new char[m_length + 1];
//用strcpy()函数实现复制
strcpy(m_value,str.m_value);
cout << this-m_value << endl;//输出测试
}
ostream & operator<<(ostream & out ,String & str)
{ out << str.m_value;
return out;
}
String::~String()
{ delete[] m_value;
}
以上就是本次的全部内容,如果帮到你的话记得点赞哟!
您的支持就是对我最大的鼓励!