简体   繁体   中英

Java String New Line Loop

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)

I'd recommend using a for loop. I think it would be easier than what you are currently doing. Generally for loops go as such:

for(START POSITION, CONTROL, ITERATION PATTERN){
    CODE
}

I'd read more about for loops here:

http://www.tutorialspoint.com/java/java_loop_control.htm

http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

The String object has a method .length() which will be used for the control of the loop. You want to iterate by 2 (because that's how you're separating it the words). You also want to start at 1 (usually the starting position is 0 but in this case we want 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);

NOTE : This will only working assuming your word variable is at least 2 in size. I'll leave that error handling up to you to write. You'll also want to handle in odd length cases as well.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM