【C/C++:字符串长度计算】

C++语言里计算字符串长度的几种方法

1.当所求字符串长度的数据类型为string类型时;
(1)使用string的.length()方法;

#include<bits/stdc++.h> 
using namespace std;
int main(){
	string s="jshshshsh";
	cout<<s.length()<<endl;
	return 0;
}
输出结果:9

(2)使用string的.size()方法(类似vector<char>容器,计算char型的个数);

#include<bits/stdc++.h> 
using namespace std;
int main(){
	string s="jshshshsh";
	cout<<s.size()<<endl;
	return 0;
}
输出结果:9

2.当字符串为char[]型时;
(1)使用strlen()方法;

#include<bits/stdc++.h> 
using namespace std;
int main(){
	char a[]="jshshshsh";
	cout<<strlen(a)<<endl;
	return 0;
}
输出结果:9

(2)使用sizeof操作符(其中末尾结束符“\0”占一个字节);

#include<bits/stdc++.h> 
using namespace std;
int main(){
	char a[]="jshshshsh";
	cout<<sizeof(a)/sizeof(a[0])<<endl;
	return 0;
}
输出结果:10

注意:
1.strlen()函数用于求字符串的有效长度,不包含末尾结束符"\0"。
2.关于sizeof:
(1)sizeof不是函数,它只是一个操作符(operator);
(2)sizeof的作用是返回一个对象或者类型所占的内存字节数(具体实现见附加);
3.在Windows 32/64位机中:
(1)char 1字节;
(2)short 2字节;
(3)int 4字节;
(4)long 4字节;
(5)在32位机中指针占4字节,而在64位机中指针占8字节;

附加:
1.关于sizeof
2.关于各类型所占字节数

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我可以帮你设计一个基本的字符串类。下面是一个示例代码: ```c++ #include <iostream> #include <cstring> using namespace std; class Mystring { private: char* str; int len; public: Mystring() { str = new char[1]; str[0] = '\0'; len = 0; } Mystring(const char* s) { len = strlen(s); str = new char[len + 1]; strcpy(str, s); } Mystring(const Mystring& other) { len = other.len; str = new char[len + 1]; strcpy(str, other.str); } ~Mystring() { delete[] str; } void print() const { cout << str << endl; } int length() const { int count = 0; for (int i = 0; str[i] != '\0'; i++) { count++; } return count; } Mystring concatenate(const Mystring& other) const { char* temp = new char[len + other.len + 1]; strcpy(temp, str); strcat(temp, other.str); Mystring result(temp); delete[] temp; return result; } }; int main() { Mystring str1("Hello"); Mystring str2("World"); Mystring str3 = str1.concatenate(str2); cout << "Length of str1: " << str1.length() << endl; cout << "Length of str2: " << str2.length() << endl; cout << "Length of str3: " << str3.length() << endl; str3.print(); return 0; } ``` 在这个示例代码中,我们定义了一个字符串类 `Mystring`,其中包含了字符串指针 `str` 和字符串长度 `len`。我们重载了构造函数、析构函数、复制构造函数以及赋值运算符。除了一般的输入输出字符串的功能外,我们还定义了计算字符串长度和连接两个字符串的功能。其中,计算字符串长度的函数 `length()` 是通过遍历 `str` 数组来实现的,而连接两个字符串的函数 `concatenate()` 是通过动态申请临时空间来实现的。 在主函数中,我们创建了三个字符串对象 `str1`、`str2` 和 `str3`,并测试了它们的长度和连接功能。输出结果为: ``` Length of str1: 5 Length of str2: 5 Length of str3: 10 HelloWorld ``` 当然,这只是一个基本的示例代码,你可以根据需要进行扩展和修改。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值