我写了一个循环遍历字符串并添加' / n'创建参数中给出的行长度。这种描述不是最好的,但很难描述,所以请看下面的代码。提前谢谢!
我的代码:
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;
}
当提供字符串&#34; Daniel&#34;并且新行长度为2这是打印到控制台时的运行:
run:
Da
n
el
BUILD SUCCESSFUL (total time: 4 seconds)
答案 0 :(得分:0)
我建议使用for
循环。我认为这比你现在做的要容易。 通常 for
循环如下:
for(START POSITION, CONTROL, ITERATION PATTERN){
CODE
}
我在这里阅读了有关for
循环的更多内容:
http://www.tutorialspoint.com/java/java_loop_control.htm
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
String
对象有一个方法.length()
,它将用于控制循环。你想迭代2(因为这就是你将它们分开的方式)。你也想从1开始(通常起始位置是0但在这种情况下我们想要1):
String word = "Daniel";//starting word
String outputWord = "";//make it empty quotes so you can concatenate to it.
//if the size of word is less than 2, then print so
//else do the code below
for(int i = 1; i < word.length(); i = i+2){
outputWord = outputWord + word.get(i-1) + word.get(i) + "\n";
}
//check if the length was of word was odd. if so, then add the last character to outputWord
System.out.println(outputWord);
注意:只有在word
变量的大小至少为2时才会生效。我会把错误处理留给你写。你也想要处理奇数长度的情况。
答案 1 :(得分:0)
这是一个简化版本
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();
}
您仍然需要了解解决方案的错误,以便从中学习并将这些知识应用到您将来编写的代码中。在调试器中逐步执行此代码和原始代码,并仔细观察发生的情况。