怎么用c++统计字符串的长度? 前提是不知道字符串的长度

来源:百度知道 编辑:UC知道 时间:2024/06/18 13:46:11
可能很长很长 不要先定义一个数组然后for(int i=0;a[i]!='\0';i++)

int mystrlen(char *str)
{
int *p=str;
for(int i=0;*p;i++,p++);
return i;
}

调用string.h中的strlen

char c;
int i=0;
while((c=getchar())!='\n') i++; //字符串中无换行符'\n'

或者

char c;
int i=0;
while((c=getchar())!=EOF) i++; //字符串中有换行符'\n'

用strlen可以直接求出字符串长度,不过要加头文件string.h

C++?推荐使用string类来存储字符串。
例子:
#include <iostream>
#include <string> //此行一定要有
using namespace std;
int main (void)
{
string a;
cin>>a;
cout<<a<<endl;
return 0;
}
输入abc输出abc 很方便
它也可以当作数组使用,如cout<<a[1]<<endl就是输出b一个字符。
测长度是其中的成员函数length()或size()。
例子:
#include <iostream>
#include <string> //此行一定要有
using namespace std;
int main (void)
{
string a;
cin>>a;
cout<<a.length()<<endl;
ret