gpt4 book ai didi

java - 有什么方法可以在 cmd 窗口中自动换行?

转载 作者:行者123 更新时间:2023-11-30 06:13:21 27 4
gpt4 key购买 nike

我和我的 friend 写了一个简单的(但真的很长)基于文本的游戏,它在 Windows 命令提示符下运行。问题是,cmd 窗口不像 Microsoft word 中那样包含任何类型的自动换行符,因此导致游戏无法玩。如果我不是很清楚,这是一个关于游戏现在如何玩的例子:

You wake up in a dark room. Wherev
er you look, you can't see anythin
g. You try to move, but you can't;
your hands are tied down by the lo
oks of it.

有什么简单的方法可以解决这个问题吗?这个游戏有 2000 多行,因此我们可能永远无法一个一个地修复句子。

编辑:为了清楚起见,我想实现以下目标:

You wake up in a dark room.
Wherever you look, you can't see
anything. You try to move, but
you can't; your hands are tied
down by the looks of it.

最佳答案

通常,宽度为 72 的行用于使文本易于阅读,因此我建议坚持这一点,而不是试图计算出文本终端的宽度。要实现正确的自动换行,您最好的选择是依赖 Apache WordUtils,它包含 wrap方法。或者(如果您不想为此下载另一个 JAR),只需将其实现复制到您的项目中:

/*
* Copyright 2002-2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
public static String wrap(String str, int wrapLength, String newLineStr, boolean wrapLongWords) {
if (str == null) {
return null;
}
if (newLineStr == null) {
newLineStr = SystemUtils.LINE_SEPARATOR;
}
if (wrapLength < 1) {
wrapLength = 1;
}
int inputLineLength = str.length();
int offset = 0;
StringBuilder wrappedLine = new StringBuilder(inputLineLength + 32);

while ((inputLineLength - offset) > wrapLength) {
if (str.charAt(offset) == ' ') {
offset++;
continue;
}
int spaceToWrapAt = str.lastIndexOf(' ', wrapLength + offset);

if (spaceToWrapAt >= offset) {
// normal case
wrappedLine.append(str.substring(offset, spaceToWrapAt));
wrappedLine.append(newLineStr);
offset = spaceToWrapAt + 1;

} else {
// really long word or URL
if (wrapLongWords) {
// wrap really long word one line at a time
wrappedLine.append(str.substring(offset, wrapLength + offset));
wrappedLine.append(newLineStr);
offset += wrapLength;
} else {
// do not wrap really long word, just extend beyond limit
spaceToWrapAt = str.indexOf(' ', wrapLength + offset);
if (spaceToWrapAt >= 0) {
wrappedLine.append(str.substring(offset, spaceToWrapAt));
wrappedLine.append(newLineStr);
offset = spaceToWrapAt + 1;
} else {
wrappedLine.append(str.substring(offset));
offset = inputLineLength;
}
}
}
}

// Whatever is left in line is short enough to just pass through
wrappedLine.append(str.substring(offset));

return wrappedLine.toString();
}

关于java - 有什么方法可以在 cmd 窗口中自动换行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32024753/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com