import java.util.ArrayList;

public class ConcatString {

public static void main(String[] args) {
        // TODO Auto-generated method stub

    ArrayList list=new ArrayList();

    String[] str={"Hello","World!!!!","Java"};
    for(int i=0;i<str.length;i++)
    {
        list.add(str[i]);
    }
    for(int i=0;i<str.length;i++)
    {
        System.out.print(list.get(i));
    }
}

Is this the right approach since i am new to java? Concat using no inbuiltin functions or + or StringBuffer...Its an interview question

有帮助吗?

解决方案 3

I assume you can't use StringBuffer and you can't use StringBuilder either, as this wouldn't make sense otherwise.

You can concat two Strings after converting them to a char array:

public String concat(String[] args){
    int length = 0;
    for (String s : args) {
        length += s.length();
    }
    char[] result = new char[length];

    int i = 0;

    for (String s : args) {
        s.getChars(0, s.length(), result, i);
        i += s.length();
    }

    return new String(result);
}

Here's how you test it:

public void testConcat() {
    String[] s = new String[3];
    s[0] = "abc";
    s[1] = "def";
    s[2] = "ghi";
    System.out.print(concat(s));

    /*
     * Output: abcdefghi
     */
}

其他提示

If your string array is large, you want to use StringBuilder, because using the += string concatenation is inefficient due to Java String immutability.

String[] str={"Hello","World!!!!","Java"};
StringBuilder sb = new StringBuilder();
for(String s : str)
{
    sb.append(s);
}
System.out.println(sb.toString());

Like this :

    String[] str={"Hello","World!!!!","Java"};
    String concat ="";
    for(String s : str)
    {
        concat+=s;
    }
    System.out.println(concat);

What is your target?.Here you simply copies the values from string array and stored it in an ArrayList.Where the code for concatination.To string concatination in java just use + operator.Don't go for complicated logic , if you have simple alternatives.

You could use one simple one of the following

String[] str = {"Hello","World!!!!","Java"};
String concat ="";
for(String s : str)
{
    concat+=s;
}
System.out.println(concat);

Or using StringBuilder which is more efficient like this:

String[] str={"Hello","World!!!!","Java"};
StringBuilder sb = new StringBuilder();
for(String s : str)
{
    sb.append(s);
}
System.out.println(sb.toString());

You dont need Arraylist for concatenation. Try the below approach

    String[] str={"Hello","World!!!!","Java"};
    StringBuilder finalString = new StringBuilder();
    for(int i=0;i<str.length;i++)
    {
        finalString.append(str[i]);
    }
    System.out.println(finalString);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top