查找字符串长度的 C++ 程序

在此示例中,您将学习计算字符串(字符串对象和 C 样式字符串)的长度(大小)。

要理解此示例,您应该具备以下 C++ 编程 主题的知识:

您可以通过使用 size() 函数或 length() 函数来获取字符串对象的长度。

size()length() 功能只是同义词,他们都做完全一样的东西。

示例:字符串对象的长度

#include <iostream>
using namespace std;

int main() {
    string str = "C++ Programming";

    // you can also use str.length()
    cout << "String Length = " << str.size();

    return 0;
}

输出

String Length = 15

示例:C 样式字符串的长度

要获取 C 字符串字符串的长度,请 strlen() 使用函数。

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    char str[] = "C++ Programming is awesome";

    cout << "String Length = " << strlen(str);

    return 0;
}

输出

String Length = 26