简体   繁体   English

在Java中合并多个字符串

[英]merging multiple Strings in java

I have a task where I'm asked to create a method that merges multiple Strings so that the first character in the first string is followed by the first character in the 2nd String followed by the first character in the 3rd string and so on. 我有一个任务,要求我创建一个合并多个字符串的方法,以便第一个字符串中的第一个字符之后是第二个字符串中的第一个字符,然后是第三个字符串中的第一个字符,依此类推。

public static String merge(String... s)

if I would merge("AH", "HI", "U") the result would be AHUHI. 如果我merge("AH", "HI", "U") ,结果将为AHUHI。 I'm just not quite sure how to deal with this problem when the amount of Strings are unknown, someone has any idea how this could be executed?¨ 当字符串的数量未知时,我不确定如何处理此问题,有人知道如何执行此操作吗?

This is what I tried: 这是我尝试的:

public static String merge(String... s)
    {
        StringBuilder b = new StringBuilder();

         for(int i = 0; i < s.length ; i++)
         {
             for(int y = 0; y < s.length ; y++)
             {
             b.append(s[y].charAt(i));
             }
         }
         return b.toString();
    }

and this is the exception I got: 这是我得到的例外:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0 线程“主”中的异常java.lang.StringIndexOutOfBoundsException:字符串索引超出范围:0

  • Find maxLength (the length of the longest String in your arguments) and change the outerloop to iterate maxLength times 查找maxLength (参数中最长的String的长度),然后更改外循环以迭代maxLength

  • Before you access a char of a String via charAt() check if the String is long enough, so you wont get the StringIndexOutOfBoundsException 在通过charAt()访问String的char之前,请检查String是否足够长,这样您就不会得到StringIndexOutOfBoundsException

Since you are already dealing with multiple input Strings, the code should work fine after these changes. 由于您已经在处理多个输入字符串,因此在进行这些更改之后,代码应该可以正常工作。

public static String merge(String... strings)
{
    int maxLength = 0;
    StringBuilder sb = new StringBuilder();

    // find the longest
    for (String s : strings)
        if (s.length() > maxLength)
            maxLength = s.length();

    // build the output string
    for (int i = 0; i < maxLength; i++)
        for (String s : strings)
            if (s.length() > i)
                sb.append(s.charAt(i));

    return sb.toString();
}

You're on the right lines, but you need to check that each string you're referencing is big enough not to throw the StringIndexOutOfBoundsException. 您处在正确的位置,但是您需要检查所引用的每个字符串是否足够大,以免引发StringIndexOutOfBoundsException。 So first, try getting the max string length: 因此,首先,尝试获取最大字符串长度:

public static String merge(String... s)
{

    int maxLen = 0;
    for (String str : s) // this loops through each string in the array s
    {
        maxLen = Math.max(maxLen, str.length());
    }

    // maxLen is now the length of the longest string;

    StringBuilder b = new StringBuilder();

    for (int i = 0; i < maxLen; ++i) // for each character position up to the max...
    {
         for (String str : s) // loop through each string:
         {
             if (str.length() > i) // check whether current string has any characters left
             {
                 b.append(str.charAt(i));
             }
         }
     }
     return b.toString();
}

Thats how I would do it: Basically, you loop though every String and always take the 1st, 2nd, 3rd, ... character of the String and append it to the StringBuilder . 那我会怎么做:基本上,你虽然循环每String并始终以第一,第二,第三,......的字符String ,并将其追加到StringBuilder

private static String merge(String... strings) {
    StringBuilder sb = new StringBuilder();
    int adv;
    boolean edited;

    adv = 0;
    edited = true;
    while (edited) {
        edited = false;
        for (String s : strings) {
            if (adv < s.length()) {
                sb.append(s.charAt(adv));
                edited = true;
            }
        }
        adv++;
    }
    return sb.toString();
}

This is how I would do it: 这就是我要做的:

public static String merge(String... s)
{
    // Here we create a StringBuilder, this will store our result string
    StringBuilder b = new StringBuilder();

    // This boolean will control when we stop appending
    boolean appended = true;

    // The outer loop will loop over the indices of the available characters
    // until we have no more characters to append
    for (int i = 0; appended; ++i) {
        // We have to default this to false to start our loop so that we don't
        // exit early
        appended = false;
        // Loop over the individual strings that we were passed
        for (String item : s) {
            // If the string we are looking at has a character at the current
            // position, we append it to our StringBuilder, otherwise we skip
            // it
            if (i < item.length()) {
                b.append(item.charAt(i));
                // Because we appeneded a character, we might have additional
                // characters, so set this so that our loop continues
                appended = true;
            }
        }
    }
    // Now we call the toString() method of StringBuilder to get a String
    // result, which we return to our caller.
    return b.toString();
}

Split each String into a array. 将每个String拆分为一个数组。 Similar to this: Split string into array of character strings 与此类似:将字符串拆分为字符串数组

Then go through the array and take out index 0 and assign it to a new string, and do that for index 1, and so on. 然后遍历数组,取出索引0,并将其分配给新字符串,然后对索引1执行此操作,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM