开发者

String Alternating letters

Im trying to write a segment of开发者_高级运维 code that will request from the user two Strings. How can i write code so that forms a new String by alternating the characters of the two Strings.

Any help is appreciated


Simple "dumb" approach :)

 class StringMerge
 {
    public static String merge(String a, String b)
    {
     if (a == null || a.length() == 0){ return b; }
     else if(b == null || b.length() == 0){ return a; }
     else
     {
        StringBuffer merged = new StringBuffer();
        int aIndex = 0;
        int bIndex = 0;
        while(aIndex < a.length() && bIndex < b.length())
        {
             merged.append(a.charAt(aIndex));
             merged.append(b.charAt(bIndex));

             aIndex++;
             bIndex++;
        }
        while(aIndex < a.length())
        {
            merged.append(a.charAt(aIndex));
            aIndex++;
        }
        while(bIndex < b.length())
        {
            merged.append(b.charAt(bIndex));
            bIndex++;
        }

        return merged.toString();
     }
    }
 }


A slightly shorter and faster [due to StringBuilder] version of mohaps' approach:

class StringMerge {
    public static String merge(final String a, final String b) {
        if (a == null || a.length() == 0) {
            return b;
        } else if (b == null || b.length() == 0) {
            return a;
        } else {
            final int aLength = a.length();
            final int bLength = b.length();
            final StringBuilder merged = new StringBuilder(aLength + bLength);

            for (int i = 0, j = 0; i < aLength && j < bLength; i++, j++) {
                merged.append(a.charAt(i)).append(b.charAt(j));
            }

            if (aLength != bLength) {
                if (aLength > bLength) {
                    merged.append(a.substring(bLength));
                } else {
                    merged.append(b.substring(aLength));
                }
            }

            return merged.toString();
        }
    }
}

Edit: Added length while creating StringBuilder instance


Pretty much the same as mohaps and shams (smile), but using an array :

static public void main(String...args) {

    Scanner scanner = new Scanner(System.in);

    System.out.print("String 1 : ");
    String s1 = scanner.nextLine();

    System.out.print("String 2 : ");
    String s2 = scanner.nextLine();

    System.out.println("Combined string is : " + mergeStrings(s1, s2));
}

static public String mergeStrings(String a, String b) {
    if (a == null) a = "";
    if (b == null) b = "";

    char[] chars = new char[a.length() + b.length()];
    int index = 0, ia = 0, ib = 0;
    while (ia<a.length() && ib<b.length()) {
        chars[index++] = a.charAt(ia++);
        chars[index++] = b.charAt(ib++);
    }
    while (ia<a.length()) {
        chars[index++] = a.charAt(ia++);
    }
    while (ib<b.length()) {
        chars[index++] = b.charAt(ib++);
    }

    return new String(chars);
}

** UPDATE **

A slightly improvement, added a start position (default to 0) to start merge at a specific position from a. If start is negative, the method will behave as if it were 0. If start is greater than the length of the string a, the string will be padded with spaces until start is reached.

static public String mergeStrings(String a, String b) {
    return mergeStrings(a, b, 0);
}

static public String mergeStrings(String a, String b, int start) {
    if (a == null) a = "";
    if (b == null) b = "";

    int len = Math.max(start - a.length(), 0) + a.length() + b.length();
    char[] chars = new char[len];
    int index = 0, ia = 0, ib = 0;

    while (ia<a.length() && ia<start) {
        chars[index++] = a.charAt(ia++);
    }
    while (index<start) {
        chars[index++] = ' ';
    }
    while (ia<a.length() && ib<b.length()) {
        chars[index++] = a.charAt(ia++);
        chars[index++] = b.charAt(ib++);
    }
    while (ia<a.length()) {
        chars[index++] = a.charAt(ia++);
    }
    while (ib<b.length()) {
        chars[index++] = b.charAt(ib++);
    }

    return new String(chars);
}

Output :

String 1 : hello
String 2 : world
Combined string is    : hweolrllod
Combined merged at 2  : helwloorld
Combined merged at 4  : helloworld
Combined merged at 10 : hello     world


Assuming the user enters two strings of the same length:

  1. Make a new, empty string.
  2. Loop...
  3. If Index % 2 == 0, take the character from the second string entered by the user and add it to the empty string.
  4. Otherwise, take the character form the first string and add it to the empty string.
  5. Stop the loop when there are no more characters to add.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜