Java如何实现按指定宽度限制每行打印的字符数
实现思路
核心逻辑是按width指定的长度对原字符串做固定步长的切片,每次切取对应长度的子串后单独打印一行即可,大部分编程语言的字符串切片方法会自动处理末尾不足width长度的场景,不需要额外做边界判断。
各语言实现示例
Python
# 定义变量 tweet = "Happy Birthday" width = 3 # 循环切片打印 for i in range(0, len(tweet), width): print(tweet[i:i+width])
JavaScript
// 定义变量 const tweet = "Happy Birthday"; const width = 3; // 循环切片打印 for (let i = 0; i < tweet.length; i += width) { console.log(tweet.slice(i, i + width)); }
Java
public class Main { public static void main(String[] args) { String tweet = "Happy Birthday"; int width = 3; for (int i = 0; i < tweet.length(); i += width) { int end = Math.min(i + width, tweet.length()); System.out.println(tweet.substring(i, end)); } } }
以上代码运行输出和你给出的示例完全一致。
内容的提问来源于stack exchange,提问作者Robertflano
相关产品推荐
相关产品推荐

