Java 试图通过迭代字符串中的每个字符来限制每行文本输出长度
我已经用java写了这篇文章,我遇到了一些麻烦 我试图将响应的行长度格式化为定义的限制。目前我的输出是几行空白。响应从单独的ArrayList中读取Java 试图通过迭代字符串中的每个字符来限制每行文本输出长度,java,Java,我已经用java写了这篇文章,我遇到了一些麻烦 我试图将响应的行长度格式化为定义的限制。目前我的输出是几行空白。响应从单独的ArrayList中读取 private void textLimiter() { String temp = new String(); String temp2 = new String(); for (int i = 0; i < reply.length(); i++){
private void textLimiter()
{
String temp = new String();
String temp2 = new String();
for (int i = 0; i < reply.length(); i++){
if(Character.isWhitespace(reply.charAt(i))){
index2=i;
if((index2 - index3) < limit){
index1 = index2;
}
if ((index2 - index3) >= limit){
temp = reply.substring(index3, index1);
System.out.println(temp);
//resets values for next itteration
index3 = index1;
}
if(i == reply.length()){
temp2 = reply.substring(index3, i);
System.out.println(temp2);
}
}
index3 = 0;
index2 = 0;
index1 = 0;
}
}
private void textLimiter()
{
字符串温度=新字符串();
String temp2=新字符串();
对于(inti=0;i=极限){
temp=应答子串(index3,index1);
系统输出打印项次(温度);
//重置下一次更新的值
index3=index1;
}
if(i==reply.length()){
temp2=应答子串(index3,i);
系统输出打印项次(temp2);
}
}
index3=0;
index2=0;
index1=0;
}
}
任何帮助都将不胜感激,谢谢
编辑:这就是变量的含义:
index1:当i对于这段代码,我从HashMap中读取,而reply是直接从HashMap中提取的响应。我将按以下方式执行:
private List<String> textLimiter(String input, int limit) {
List<String> returnList = new ArrayList<>();
while (input.length() > limit) {
returnList.add(input.substring(0, limit);
input = input.substring(limit, input.length() - limit);
}
returnList.add(input);
}
然后将打印以下内容:
This
is
a te
st
如果这不是您的意思,那么请在您的问题中添加示例输入和输出
更新:根据新的要求,我会这样做:
for (String line : textLimiter("This is a test", 4)) {
System.out.println(line);
}
private List<String> textLimiter(String input, int limit) {
List<String> returnList = new ArrayList<>();
String[] parts = input.split(" ");
StringBuilder sb = new StringBuilder();
for (String part : parts) {
if (sb.length() + part.length() > limit) {
returnList.add(sb.toString().substring(0, sb.toString().length() - 1));
sb = new StringBuilder();
}
sb.append(part + " ");
}
if (sb.length() > 0) {
returnList.add(sb.toString());
}
return returnList;
}
输出:
If you turn left
then you should see
the corner at the
end of the road.
你想用空格填充简短的回答,这样所有的回答都是相同的长度?!您不应该需要编写
newstring()
,事实上,他们不应该将其添加到API中。尝试String temp=“”相反,试图理解一个只使用名为index1、index2、index3、temp1和temp2的变量的代码并不容易。给变量起一个有意义的名字。还有,我不明白你想达到什么目的。如果只想打印字符串的前N个字符,请使用substring()并打印结果。如果您想要的不同,则显示示例输入和输出。无论如何,index3
在前两个If语句中始终为0。我真的不理解你的代码……一个示例输入是“如果你向左拐,那么你应该看到路的尽头。”这将从另一个类中存储的hashmap中读取。理想的格式是一行小于限制的整字。有时,只要限制允许,我需要几行。
If you turn left
then you should see
the corner at the
end of the road.