0

I'm trying to join an array of Strings using the String.join() method. I need the first item of the array to be removed (or set to empty). If I have a string array such as {"a","b","c","d"}, I want to return only b.c.d.

If it can be done with a for loop, that is fine. I currently have:

for (int i=1; i<item.length; i++) { newString += item[i] + "."; } 

6 Answers 6

4

Try using Arrays.copyOfRange to skip the first element of the array:

String.join(".", Arrays.copyOfRange(item, 1, item.length)); 

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

doctor livingstone I presume? A master come into view. +1
Tim that is perfect and exactlty what I was looking for. Bonus points for keeping it syntactically short also!
2

You can do it as follows:

String.join(".", Arrays.stream(myArray, 1, myArray.length).collect(Collectors.toList())); 

or if you want the . suffix in the result then use joining collector:

Arrays.stream(myArray, 1, myArray.length) .collect(Collectors.joining(".","",".")); 

4 Comments

I think that trailing dot is a period (punctuation) and not part of the desired output.
@TimBiegeleisen Right, Thanks. just wanted to make sure :)
IMHO, performance is more important. That's why I can't give +1. It seems to me not so competent.
@snr using the String.join Tims approach is definitely better. I always keep forgetting you can pass an array to the join method. nevertheless, I don't want to change it now as Tim answered it first. but if you're concerned about the list construction then one can do Arrays.stream(myArray, 1, myArray.length) .collect(Collectors.joining("."));
1

An alternative with streams:

String result = Arrays.stream(item) .skip(1) .collect(joining(".")); 

Comments

0

Or this can also be a possible answer

String.join(".",myarray).substring(myarray[0].length()+1); 

Comments

0

try this

String[] a = new String[] {"a","b","c","d"}; String newString = ""; for (int i=1; i<a.length; i++) { if (i > 0) { newString += a[i] + "."; } } System.out.println(newString); 

Comments

0

try using following code

public static String getJoined(String []strings) { StringBuilder sbr = new StringBuilder(); // to store joined string // skip first string, iterate over rest of the strings. for(int i=1; i<strings.length; i++) { // append current string and '.' sbr.append(strings[i]).append("."); } // remove last '.' , it will not be required. // if not deleted the result will be contain '.' at end. // e.g for {"a","b","c"} the result will be "b.c." instead of "b.c" sbr.delete(sbr.length()-1, sbr.length()); return sbr.toString(); } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.