Home > other >  Use of string buffers/join
Use of string buffers/join

Time:10-04

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);
    
       }
    }

CodePudding user response:

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());
}

CodePudding user response:

Just us String#concat() within an enhanced for loop:

public static String concatArray(String[] strings) {    
    String str = "";
    for (String s : strings) {
        str = str.concat(s);
    }
    return str;
}

You could also String#join() and just do:

public static String concatArray(String[] strings) { 
    return String.join("", strings);
} 

Or you could do this, where the method accepts varArgs. A comma delimited list of strings can be supplied or a string[] array:

public static String concat(String... strings) {
    /* Make sure a non-null String array or 
       varArgs of strings are supplied.  */
    if (strings == null || strings.length == 0) {
        return null;  //return null if not.
    }
    
    return String.join("", strings);
}   

To use:

System.out.println(concat("f", "o", "o", "bar", "ability"));

// OR    

String[] stringsArray = {"f", "o", "o", "bar", "ability"};
System.out.println(concat(stringsArray);

Both produce the same output to Console:

foobarability
  • Related