【问题标题】:How to find length of a string如何查找字符串的长度
【发布时间】:2015-12-08 11:16:52
【问题描述】:

我如何使用数据类型“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;
}

【问题讨论】:

  • 应该工作得很好,你有什么问题?
  • 错误的标题,将#include &lt;string&gt;更改为#include &lt;cstring&gt;。另一个用于std::string 类,而不是 c-string 函数。

标签: c++ string string-length


【解决方案1】:

如果您使用的是 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:您发布的代码对我有用。

【讨论】:

    猜你喜欢
    • 2017-06-13
    • 2013-05-03
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多