Thursday, 19 March 2020

Java: Convert array of strings to a string

Approach 1: Traverse the string array and append element one by one.
public static String getString_approach1(String[] inputArray, String separator) {
 if(inputArray == null || inputArray.length == 0 || separator == null) {
  return null;
 }
 
 StringBuilder builder = new StringBuilder();
 
 for(String ele: inputArray) {
  builder.append(ele).append(separator);
 }
 
 String result = builder.toString();
 int separatorLength = separator.length();
 
 return result.substring(0, result.length()-separatorLength);
}

Approach 2: Using String.join()
public static String getString_approach2(String[] inputArray, String separator) {
 if (inputArray == null || inputArray.length == 0 || separator == null) {
  return null;
 }

 return String.join(separator, inputArray);
}

Find the below working application.

App.java
package com.sample.app;

public class App {

 public static String getString_approach1(String[] inputArray, String separator) {
  if (inputArray == null || inputArray.length == 0 || separator == null) {
   return null;
  }

  StringBuilder builder = new StringBuilder();

  for (String ele : inputArray) {
   builder.append(ele).append(separator);
  }

  String result = builder.toString();
  int separatorLength = separator.length();

  return result.substring(0, result.length() - separatorLength);
 }

 public static String getString_approach2(String[] inputArray, String separator) {
  if (inputArray == null || inputArray.length == 0 || separator == null) {
   return null;
  }

  return String.join(separator, inputArray);
 }

 
 public static void main(String args[]) {

  String[] msgs = { "Hello", "How", "Are", "You" };

  String result1 = getString_approach1(msgs, " ");
  String result2 = getString_approach1(msgs, " ");
  
  System.out.println(result1);
  System.out.println(result2);

 }

}

Output
Hello How Are You
Hello How Are You


You may like

No comments:

Post a Comment