C++计算字符串长度包含空格 - 使用std::string::length()
C++计算字符串长度包含空格:使用 std::string::length()
想要计算 C++ 字符串中包含空格的字符数量?答案是使用 std::string 类的 length() 函数,而不是 size() 函数。这两个函数实际上是等效的,返回的结果相同,但为了代码清晰易懂,建议统一使用 length() 计算字符串长度。
以下是使用 length() 函数计算包含空格的字符串长度的示例:
#include <iostream>
#include <string>
int main() {
std::string sentence;
std::cout << 'Enter a sentence: ';
std::getline(std::cin, sentence);
std::cout << 'Length of the sentence (including spaces): ' << sentence.length() << std::endl;
return 0;
}
代码解释:
#include <iostream>和#include <string>: 这两行代码引入了必要的头文件。iostream用于输入输出操作,string用于使用字符串。std::string sentence;: 声明一个名为sentence的字符串变量,用于存储用户输入的句子。std::cout << 'Enter a sentence: ';: 提示用户输入一个句子。std::getline(std::cin, sentence);: 使用std::getline()函数从标准输入流 (std::cin) 读取一行文本,包括空格,并将读取的内容存储到sentence变量中。std::cout << 'Length of the sentence (including spaces): ' << sentence.length() << std::endl;: 这行代码计算并输出句子的长度,包括空格。sentence.length()返回字符串中字符的数量,包括空格。
总结
使用 std::string::length() 函数可以轻松计算 C++ 字符串中包含空格的字符数量。请记住,length() 返回一个无符号整数类型 (std::size_t),表示字符串中字符的数量。
希望这个例子能够帮助你!如果你还有其他关于字符串处理、C++ 或编程的问题,请随时提问。
原文地址: http://www.cveoy.top/t/topic/crYP 著作权归作者所有。请勿转载和采集!