C++ 获取字符串行数
要获取字符串的行数,可以按照以下步骤进行操作:
- 将字符串分割成多个子字符串,每个子字符串代表一行。可以使用
std::istringstream和std::getline函数来实现这一步骤。具体代码如下:
#include <iostream>
#include <sstream>
#include <string>
int getLineCount(const std::string& str) {
std::istringstream iss(str);
std::string line;
int count = 0;
while (std::getline(iss, line)) {
count++;
}
return count;
}
int main() {
std::string str = "Hello\nWorld\nC++";
int lineCount = getLineCount(str);
std::cout << "Line count: " << lineCount << std::endl;
return 0;
}
-
使用一个计数器变量来记录行数,每次成功地从字符串中读取一行时,计数器变量加1。
-
返回计数器变量的值,即为字符串的行数。
在上述代码中,我们使用std::istringstream将字符串转换为输入流,并使用std::getline从输入流中读取每一行。每次调用std::getline成功读取一行后,计数器变量count加1。最后返回计数器变量count的值,即为字符串的行数
原文地址: https://www.cveoy.top/t/topic/ijyR 著作权归作者所有。请勿转载和采集!