字符串按行读取,通常指将一个字符串按照行进行分隔,每行的内容单独存储。在不同的编程语言中,实现方式可能有所差异,下面介绍几种常用的实现方式:

  1. Python中使用splitlines()方法:
s = 'hello\nworld\npython'
lines = s.splitlines()
for line in lines:
    print(line)

输出:

hello
world
python
  1. Java中使用split()方法:
String s = 'hello\nworld\njava';
String[] lines = s.split("\r?\n");
for (String line : lines) {
    System.out.println(line);
}

输出:

hello
world
java
  1. 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
  1. JavaScript中使用split()方法:
let s = 'hello\nworld\njavascript';
let lines = s.split(/\r?\n/);
for (let line of lines) {
    console.log(line);
}

输出:

hello
world
javascript
字符串按行读取 - Python, Java, C++, JavaScript 实现方法

原文地址: https://www.cveoy.top/t/topic/nwSd 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录