Home » Android » android – How to concatenate 2 or more strings as one inside a string array in Java?

android – How to concatenate 2 or more strings as one inside a string array in Java?

Posted by: admin June 15, 2020 Leave a comment

Questions:

I’d like to concatenate 2 or more consecutive strings into one string in an array according to two variables x and y meaning that starting from the x:th element, concatenate, until we have concatenated y elements. For example, if an Array ‘A’ has elements as:

A = {"europe", "france", "germany", "america"};
x=2;y=2;
//Here, I want to concatenate france and germany as :
A = {"europe", "france germany", "america"};
//Or 
x=2,y=3;

A= {"europe", "france germany america"};

Like this. Anyone know How This can be done without complex programming?

How to&Answers:

Probably the most concise way is:

  1. Construct an array of the right size:

    String[] result = new String[A.length - (y-1)];
    
  2. Copy the start and the end of the array using System.arraycopy:

    System.arraycopy(A, 0, result, 0, x-1);
    System.arraycopy(A, x+y-1, result, x+1, A.length-(x+1));
    
  3. Build the concatenated string:

    result[x-1] = String.join(" ", Arrays.asList(A).subList(x-1, x-1+y));
    

(Note: out by one errors may be present, owing to the date of writing)

Answer:

Here is a working script, though I don’t know how simple you would consider it to be. The algorithm is to simply walk down the input array, copying over strings to the output, until we reach the first entry as determined by the x value. Then, we concatenate the y number of terms to a single string. Finally, we finish by copying over the remaining terms one-by-one.

public static String[] concatenate(String[] input, int x, int y) {
    List<String> list = new ArrayList<>();
    // just copy over values less than start of x range
    for (int i=0; i < x-1; ++i) {
        list.add(input[i]);
    }

    // concatenate y values into a single string
    StringBuilder sb = new StringBuilder("");
    for (int i=0; i < y; ++i) {
        if (i > 0) sb.append(" ");
        sb.append(input[x-1+i]);
    }
    list.add(sb.toString());

    // copy over remaining values
    for (int i=x+y-1; i < input.length; ++i) {
        list.add(input[i]);
    }
    String[] output = new String[list.size()];
    output = list.toArray(output);

    return output;
}

String[] input = new String[] {"europe", "france", "germany", "america"};
int x = 2;
int y = 3;
String[] output = concatenate(input, x, y);
for (String str : output) {
    System.out.println(str);
}

Demo

Answer:

Here is a very straightforward procedural approach:

private static ArrayList<String> concatenate(String[] strings, int x, int y) {
    ArrayList<String> retVal = new ArrayList<>();
    StringBuilder builder = new StringBuilder();
    int count = y;
    boolean concatenated = false;
    for (int i = 0 ; i < strings.length ; i++) {
        if (i < x - 1 || concatenated) {
            retVal.add(strings[i]);
        } else {
            builder.append(" ");
            builder.append(strings[i]);
            count--;
            if (count == 0) {
                retVal.add(builder.toString());
                concatenated = true;
            }
        }
    }
    return retVal;
}

Explanation:

  • For each element in the inout array:
  • Add the element to the return value if we haven’t reached the x - 1 index or we have finished concatenating.
  • If we reached x - 1 and not finished concatenating, add the element to the string builder.
  • If we finished concatenating (indicated by count == 0), add the concatenated string to the return value.

Answer:

Possible with Lists.

public static void main(String[] args) {
    String arr []= {"europe", "france", "germany", "america"};
    int from =1;
    int toAdd =3;
    int len = arr.length;

    if(from+toAdd>len){
        //show error
        return ;
    }
    List<String> list = Arrays.asList(arr);
    List<String> concatList = list.subList(from, from+toAdd);
    StringBuilder sb = new StringBuilder();
    for(String st: concatList){
        sb.append(st).append(" ");
    }
    List<String>outList = new ArrayList<>(list.subList(0, from));
    outList.add(sb.toString());
    if(from+toAdd<len-1){
        outList.addAll(list.subList(from+toAdd, list.size()-1));
    }
    System.out.println(outList);
}

Answer:

It should be done using a for loop and keeping tract of indices

String[] A = {"europe", "france", "germany", "america"};

String[] new_Array;
// your code goes here
int x=2,y=3;
int start_concat = x-1 ; // to account for array index

int stop_concat = start_concat+y;

new_Array = new String[A.length-y + 1];

for(int i=0; i<=start_concat; i++){   
     new_Array[i] = A[i];
}

for(int i = start_concat+1 ; i<stop_concat; i++){
    new_Array[start_concat] = new_Array[start_concat] + A[i];
}

for(int i =start_concat+1, j=stop_concat ; i< new_Array.length;i++,j++){
    new_Array[i] = A[j];
}

for(int i=0; i<new_Array.length; i++){
    System.out.println(new_Array[i]);
}

See my snippet on ideone

Answer:

Using the List API we can leverage the subList method as well as the addAll method to modify a particular section of a list and insert elements into a list at the specified position.

Along with that, we utilise the String replace method to remove the redundant string representation of a list and finally convert the accumulator list into an array of strings.

public static String[] concatElements(String[] elements, int start, int count){

       List<String>  accumulator = new ArrayList<>(Arrays.asList(elements));
       List<String> subList = new ArrayList<>(accumulator.subList(--start, start + count));
       accumulator.removeAll(subList);

       String concatenatedElements = subList.toString()
                      .replace(",", "")
                      .replace("[","")
                      .replace("]", "");

       subList = Collections.singletonList(concatenatedElements);
       accumulator.addAll(start, subList);
       String[] resultSet = new String[accumulator.size()];

       for (int i = 0; i < accumulator.size(); i++) {
            resultSet [i] = accumulator.get(i);
       }
       return resultSet;
}

calling it like so:

System.out.println(Arrays.toString(concatElements(array, 2, 2)));

will produce:

[europe, france germany, america]

and calling it like so:

System.out.println(Arrays.toString(concatElements(array, 2, 3)));

will produce:

[europe, france germany america]

As is, there is no validation for the parameter start and count but I leave that as an exercise for you.

Answer:

To concatenate Strings in Android we can use TextUtils.copyOfRange() class. For the rest we can go with System.arraycopy() method to avoid loops:

public static String[] concatenate(String[] input,
                                   int from, // starts from 0 position
                                   int number){
    String[] res = new String[input.length - number + 1];

    int to = from + number;

    System.arraycopy(input, 0, res, 0, from);

    String[] sub = Arrays.copyOfRange(input, from, to);
    String joined = TextUtils.join(" ", sub);
    res[from] = joined;

    System.arraycopy(input, to, res, from + 1, input.length - to);

    return res;
}

Answer:

Another alternative using the java.util.stream library:

This uses IntStream.range to decide the new size of the output List, and to generate ints representing indexes in the output sequence.

Then .mapToObj is used for each output index to decide what to put in each respective position (output only has a single index for the joined strings).

There are essentially 3 possibilities for the output – which are decided by the getOrMergeData method:

  • Before index of the joined strings – use data[index]
  • After index of the joined strings – use data[index + count - 1]
  • At index of the joined strings – use Arrays.copyOfRange and string.Join to join the strings which need to be merged together.

Click for Running Example:

class Main {
  public static void main(String[] args) {
    String [] data = {"europe", "france", "germany", "america"};
    int startIndex = 1;
    int count = 2;
    int newSize = data.length - count + 1;

    List<String> output =
        IntStream.range(0, newSize)
                 .mapToObj(n -> Main.getOrJoin(data, startIndex, count, n))
                 .collect(Collectors.toList());

    for (String s : output) {
      System.out.println(s);
    }
  }

  private static String getOrJoin(String[] data, int joinIndex, int count, int index) {
    if (index < joinIndex) return data[index];
    else if (index > joinIndex) return data[index + count - 1];
    else {
        String[] dataToJoin = Arrays.copyOfRange(data, joinIndex, joinIndex + count);
        return String.join(" ", dataToJoin);
    }
  }
}

Output:

europe
france germany
america