如何找到字符串的长度
How to find length of a string
如何使用数据类型“char”找到字符串的长度?我试了很多次,但没有成功。我也看到了 cplusplus 教程,但无法修复下面的示例
#include <stdio.h>
#include <iostream>
#include<string>
using namespace std;
int main() {
char str1[80];
char str2[80];
cout << "Enter string 1 : ";
cin.getline(str1,80); cout << endl;
cout << "Enter string 2 : ";
cin.getline(str2,80);cout << endl;
cout << "String 1 is :-> " << (unsigned)strlen(str1) << endl;
cout << "String 1 is :-> " << (unsigned)strlen(str2) << endl;
}
如果您使用的是 C++,我强烈建议不要使用 char*
来处理字符串,而是开始使用 std::string
。
string str1;
string str2;
cout << "Enter string 1 : ";
cin >> str1; cout << endl;
cout << "Enter string 2 : ";
cin >> str2; cout << endl;
cout << "String 1 is :-> " << str1.size() << endl;
cout << "String 2 is :-> " << str2.size() << endl;
PS:您发布的代码对我有用。
如何使用数据类型“char”找到字符串的长度?我试了很多次,但没有成功。我也看到了 cplusplus 教程,但无法修复下面的示例
#include <stdio.h>
#include <iostream>
#include<string>
using namespace std;
int main() {
char str1[80];
char str2[80];
cout << "Enter string 1 : ";
cin.getline(str1,80); cout << endl;
cout << "Enter string 2 : ";
cin.getline(str2,80);cout << endl;
cout << "String 1 is :-> " << (unsigned)strlen(str1) << endl;
cout << "String 1 is :-> " << (unsigned)strlen(str2) << endl;
}
如果您使用的是 C++,我强烈建议不要使用 char*
来处理字符串,而是开始使用 std::string
。
string str1;
string str2;
cout << "Enter string 1 : ";
cin >> str1; cout << endl;
cout << "Enter string 2 : ";
cin >> str2; cout << endl;
cout << "String 1 is :-> " << str1.size() << endl;
cout << "String 2 is :-> " << str2.size() << endl;
PS:您发布的代码对我有用。