You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 09:45:04