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?
In order to combine (concatenate) two arrays, we find its length stored in aLen and bLen respectively. Then, we create a new integer array result with length aLen + bLen . Now, in order to combine both, we copy each element in both arrays to result by using arraycopy() function.
Using CONCATENATE in Excel - things to remember In one formula, you can concatenate up to 255 strings, a total of 8,192 characters. The result of the CONCATENATE function is always a text string, even when all of the source values are numbers.
Using the + operator is the most common way to concatenate two strings in Java.
Probably the most concise way is:
Construct an array of the right size:
String[] result = new String[A.length - (y-1)];
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));
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)
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With