문제

I'm stumped and have no idea how to do this. I'm creating a method that will take a String[] as an argument and build it into a string. Then my main method will use the output from this method as name for a fileWriter. The rest of the code is in place.

public static String nameFromString (String[] args){
    StringBuilder builder = new StringBuilder();
    for (int i = 1; i < args.length; i++) {
        builder.append(args[i]);
        builder.append(" ");
    }
    return builder.toString();  
}

If I, for example, write "new My File" in my program, it uses "My file" as a name and the main method appends a ".txt". So far, no problems.

But my problem, right now, is that it names the file "My File .txt" and also, when reading a file, using this same method, it tries to read "File name .txt" instead of "File name.txt".

How do I remove this last space in the string?

도움이 되었습니까?

해결책 3

One way is to make the call to append conditional on the loop index:

for (int i = 1; i < args.length; i++) {
    builder.append(args[i]);
    if (i < args.length - 1) {
      builder.append(" ");
    }
}

다른 팁

You can use the String.trim() method to remove leading and trailing spaces.

String str = " ab c  ".trim(); // -> "ab c"

I see a lot of answers with index or buffer checking here. I just want to share a piece of code I use often and it is based on Guava Joiner class:

String result = Joiner.on(' ').join(args);

It is really small and clever solution from Google. Also it is optimized and uses StringBuilder inside..

You could use an "insert", or you could modify your append or you could trim() as follows

APPEND very similar to your initial just add the if.

if (i + 1 < args.length) { // added if.
  builder.append(" ");
}

"INSERT" change the loop a little

for (int i = 1; i < args.length; i++) {
  if (i != 1) {
    builder.append(" ");
  }
  builder.append(args[i]);
}

TRIM change the return like this

return builder.toString().trim();  

There are a number of ways this can be achieved. I use to delete the last character from the StringBuilder after the loop had completed, but this requires you to ensure that the last character is a space, instead, I know use...

for (int i = 1; i < args.length; i++) {
    if (builder.length() > 0) {
        builder.append(" ");
    }
    builder.append(args[i]);
}

The easiest is to append one string ahead and then continue just toggling the append sequence:

if(args.length < 2)return "";

StringBuilder builder = new StringBuilder(args[1]);

for (int i = 2; i < args.length; i++) {
        builder.append(" ");
        builder.append(args[i]);

    }

return builder.toString();
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top