字符串 按行读取
字符串按行读取,通常指将一个字符串按照行进行分隔,每行的内容单独存储。在不同的编程语言中,实现方式可能有所差异,下面介绍几种常用的实现方式:
- Python中使用splitlines()方法:
s = "hello\nworld\npython"
lines = s.splitlines()
for line in lines:
print(line)
输出:
hello
world
python
- Java中使用split()方法:
String s = "hello\nworld\njava";
String[] lines = s.split("\\r?\\n");
for (String line : lines) {
System.out.println(line);
}
输出:
hello
world
java
- C++中使用getline()方法:
#include <iostream>
#include <string>
#include <sstream>
int main() {
std::string s = "hello\nworld\ncpp";
std::istringstream ss(s);
std::string line;
while (std::getline(ss, line)) {
std::cout << line << std::endl;
}
return 0;
}
输出:
hello
world
cpp
- JavaScript中使用split()方法:
let s = "hello\nworld\njavascript";
let lines = s.split(/\r?\n/);
for (let line of lines) {
console.log(line);
}
输出:
hello
world
javascript
``
原文地址: https://www.cveoy.top/t/topic/cwZk 著作权归作者所有。请勿转载和采集!