java 字符串 换行,Java字符串换行

I wrote a method that loops through a string and adds '/n' to create a line length that was given in the parameters. That description is not the best but it's hard to describe so look at the code below. Thanks in advance!

My Code:

public static String lineLength(String str, int length){

int totalLength = 0; //total length of the document

int lengthConst = 0; //constant value of the length for the loop

int nLength = 0; // length of \n = 2 characters

String work1, work2; //Strings to work with in the loop. Used as string buffers in substrings

if(str != null){

totalLength = str.length();

lengthConst = length;

}

if(length < 1){

throw new NullPointerException("Length must be >= 1");

}

/*

Main Loop: check again if length is not zero, check if totalLength is not zero,

check if pseudoCursor is not zero, check if length is less than or equal to totalLength

*/

while((length != 0) && (totalLength != 0) && (lengthConst != 0) && (length <= totalLength)){

work1 = str.substring(0, length); //store string of beginning to line length

work2 = str.substring(length + nLength, str.length()); //store string from length to end

work1 = work1.concat("\n"); //add new line

str = work1.concat(work2); //add work1 and work2 and store in str

nLength += 1; //nLength increases by 2 because we are going to add another \n

length += length;

}

return str;

}

When provided with the string "Daniel" and the new line length of 2 this is the run when printed to the console:

run:

Da

n

el

BUILD SUCCESSFUL (total time: 4 seconds)

解决方案

Here's a much simplified version

public static String lineLength(String str, int length) {

StringBuilder sb = new StringBuilder();

while(true) {

if(str.length() <= length) {

sb.append(str);

break;

}

sb.append(str.substring(0, length));

sb.append("\n");

str = str.substring(length);

}

return sb.toString();

}

You still need to understand what was wrong with your solution so that you learn from it and can apply that knowledge to the code you write in the future. Step through both this and your original code in a debugger and observe carefully what is happening.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值