Issue
StringUtils.concat(String[] strings) should join character strings end to end. For example, from an array which contains "f", "o", "o", "bar" it should result "foobar". Input: strings always contains at least one element. Implement StringUtils.concat(String[] strings).
I'm new in Java I'm trying to solve string join method Can you please guide me what i'm doing wrong and how I can solve this problem?
public class StringUtils {
static String concat(String[] strings) {
strings=strings.length;
String res="";
for(int i=0;i<strings.length;i++) {
res=res+strings.length;
}
return res;
}
public static void main (String[] args) {
/* concatenates the given array of strings*/
String[] array = {"f","o","o","bar"};
String result = StringUtils.concat(array);
}
}
Solution
Instead of adding the length of the array, you should add the strings of the array:
static String concat(String[] strings) {
String res = "";
for (int i = 0; i < strings.length; i++) {
res += strings[i]; // Shorthand for res = res + strings[i]
}
return res;
}
There is a better way to iterate the array using the for-each loop:
static String concat(String[] strings) {
String res = "";
for (String str : strings) {
res += str;
}
return res;
}
You can even use the Stream API
static String concat(String[] strings) {
return Arrays.stream(strings).collect(Collectors.joining());
}
Answered By - Arvind Kumar Avinash
Answer Checked By - Mary Flores (JavaFixing Volunteer)