Reputation: 8376
I need to grab the whole arguments sequence as one single String, I'm using the following code, replacing commas and both square brackets.
Arrays.toString(args).replace(",", "").replace("[", "").replace("]", "");
Let's say I run it with the following arguments:
Hello, you're a programmer, you're a great guy
By using Arrays.toString()
I'm getting:
[Hello, you're, a, programmer,, you're, a, great, guy]
So, by using the .replace()
I actually get:
"Hello, you're a programmer, you're a great guy"
I just find the above code so messy, eventhough is working. How could I reduce such sentence in only one method?
Upvotes: 1
Views: 4547
Reputation: 974
You could
main()
, specifically how it takes arguments (I'm not sure this is possible or feasible).toString()
that behaves differentlyThe last is probably the least work, especially if you don't plan on using it much.
Upvotes: 0
Reputation: 103
Are you for some reason splitting strings by their commas then putting them into an ArrayList? Any how, to answer the question specifically without trying to guess all the bad things going on...
You can probably do it taking out one replace but... meh.
public static void main(String[] args) {
ArrayList<String> myArray = new new ArrayList<String>();
myArray.add("hello");
myArray.add("I");
myArray.add("Am");
myArray.add("Ben");
myArray.add("!");
System.out.println(myArray.toString().replaceAll("\\[(.*)\\]", "$1").replaceAll(",", ""));
}
Upvotes: 0
Reputation: 67
Arrays of Strings can be converted to single String as given below.
StringBuilder builder = new StringBuilder();
for (String str: args)
{
builder.append(str);
}
System.out.println(builder.toString());
Upvotes: 0
Reputation: 262474
I like Commons Lang's StringUtils#join:
join(args);
, or, if you need a separator between the parts
join(args, ' ');
But I think you are asking the wrong question. If you want to preserve a String passed in from the command line exactly as is, you need to quote it in the shell. You will then get the whole thing as a single first String in the argument array. Otherwise, there is no way to recover for example consecutive spaces:
java -jar MyApp.jar "Hello, you're a programmer, you're a great guy"
Upvotes: 3
Reputation: 825
I would recommend using a StringBuilder. It's efficient, especially if you create the instance with the total length of your strings (check in a loop) as a constructor parameter.
For more info check: http://docs.oracle.com/javase/tutorial/java/data/buffers.html
Upvotes: 0