📌  相关文章
📜  计算字符串中的字符数 c++ (1)

📅  最后修改于: 2023-12-03 15:12:02.285000             🧑  作者: Mango

计算字符串中的字符数

在C++中,我们可以通过以下方法来计算字符串中的字符数:

#include <iostream>
#include <cstring>

using namespace std;

int main() {
    char str[] = "hello world";
    int len = strlen(str);
    cout << "The length of the string is: " << len << endl;
    return 0;
}

上面的代码通过调用strlen()函数来获取字符串的长度,然后输出到控制台。当然,我们可以自己实现计算字符串长度的函数,如下所示:

#include <iostream>
#include <cstring>

using namespace std;

int getLength(char* str) {
    int len = 0;
    while (*str) {
        len++;
        str++;
    }
    return len;
}

int main() {
    char str[] = "hello world";
    int len = getLength(str);
    cout << "The length of the string is: " << len << endl;
    return 0;
}

这个函数使用了指针来遍历字符串中的每个字符,并累计计数器的值。需要注意的是,当指针指向字符串的结尾时,循环将停止。

总的来说,计算字符串中的字符数并不是一个难题,在C++中有现成的函数可以使用,也可以自己写一个函数来实现。