Home > Software engineering >  Trying to alternate two strings together in Java
Trying to alternate two strings together in Java

Time:05-12

/* Programs goal is to take two strings and use a method to alternate the characters.

  • example - "test" "case" -> "tceasste"
  • Sorry I tried looking at other similar questions but I didn't understand how they worked as I am very new to Java and coding in general. */
public class MyProgram extends ConsoleProgram
{
    public void run()
    {
        System.out.println(sCombine("test","case")); //"tceasste"
        System.out.println(sCombine("avalanche","dog")); //"advoaglanche"
        System.out.println(sCombine("","water")); //"water"
        
    }
    
    public String sCombine(String a, String b)
    {
        String result = "";
        
        int lengtha = a.length();
        int lengthb = b.length();
        int lengthc = 0;
        if(lengtha < lengthb)
        {
            lengthc = lengtha;
        }
        else
        {
            lengthc = lengthb;
        }
        
        
        for(int i = 0; i < lengthc; i  )
        {
            char currentA = a.charAt(i);
            char currentB = b.charAt(i);
            
            result  = a;
            result  = b;
        }
        return result;
    }
}

CodePudding user response:

You can use a loop that iterates the maximum length of both the strings. Then you can extract the individual character at the ith position and add it alternatively to a resulting String object. I have used StringBuiler as it mutable( diff here ) This is the code that I have attached.

public class MyProgram {
    public static void main(String[] args) {
        System.out.println(sCombine("test", "case")); // "tceasste"
        System.out.println(sCombine("avalanche", "dog")); // "advoaglanche"
        System.out.println(sCombine("", "water")); // "water"

    }

    public static String sCombine(String a, String b) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < Math.max(a.length(), b.length()); i  ) {
            char aChar = i < a.length() ? a.charAt(i) : '#';
            char bChar = i < b.length() ? b.charAt(i) : '#';
            if (aChar != '#') {
                result.append(aChar   "");
            }
            if (bChar != '#') {
                result.append(bChar   "");
            }
        }
        return result.toString();
    }
}

and the output is :

tceasste
advoaglanche
water

CodePudding user response:

The problem is that you're doing:

    result  = a;

You need to do:

    result  = currentA;

I would also suggest looking at the StringBuilder class. It has a lot of built in functionality for things of this nature :)

CodePudding user response:

You can use substring to savely append the remainder of the Strings. Should the limit be out of bounds, no exception will be thrown, because substring will just return an empty String.

public String sCombine(String a, String b) {

  final StringBuilder builder = new StringBuilder();
  final int min = Math.min(a.length(), b.length());

  for (int i = 0; i < min; i  ) {
    builder.append(a.charAt(i)).append(b.charAt(i));
  }

  builder.append(a.substring(min)).append(b.substring(min));

  return builder.toString();
}

CodePudding user response:

Just another way. Read all the comments in code:

/**
 * Sequentially blends two strings together one character at a time, for 
 * example, if the first argument was "cat" and the second argument was 
 * "dog" then the returned result will be: "cdaotg".<br><br>
 * 
 * <b>Example Usage:</b><pre>
 *     {@code  
 *      final String a = "cat";
 *      final String b = "elephant";
 *      String newString = sCombine(a, b);
 *      System.out.println(newString); 
 *      // Console will display: cealte }
 * 
 *      OR 
 *     {@code  
 *      final String a = "cat";
 *      final String b = "elephant";
 *      String newString = sCombine(a, b, true);  // true is optionally supplied here.
 *      System.out.println(newString); 
 *      // Console will display: eclaetphant }</pre>
 * 
 * @param stringA (String) The first String to blend.<br>
 * 
 * @param stringB (String) The second String to blend.<br>
 * 
 * @param startWithLongest (Optional - boolean varArgs) Default is false <pre>
 *                         whereas this method will always take the first 
 *                         supplied argument and blend the second argument 
 *                         into it. In this default situation, the first 
 *                         argument is always considered to contain the 
 *                         longest String. If however, the second argument 
 *                         contains more characters then the those extra 
 *                         characters will be truncated, for example: "cat" 
 *                         and "elephant". Result will be: "cealte". It would 
 *                         be beneficial to always pass the longest string as 
 *                         the first argument in order to achieve the result 
 *                         of: "eclaetphant".
 *         
 *                         If boolean true is supplied to this optional parameter 
 *                         then the longest argument passed to this method will 
 *                         always be considered as the first argument rather than 
 *                         the first supplied argument, for example: "cat" as the 
 *                         first argument and "elephant" as the second argument 
 *                         and true as the third argument will return a result 
 *                         of "eclaetphant".
 * 
 *                         Supplying nothing forces default to be used.</pre>
 * 
 * @return (String) The blended String;
 */
public static String sCombine(final String stringA, final String stringB, 
                                  final boolean... startWithLongest) {
    String strgA = stringA, strgB = stringB; // So to maintain original Strings
    /* If `true` is supplied to the startWithLongest optional 
    vararg parameter then ensure the String argument with the 
    most characters is the first argument (if true, always place 
    the longest first).                           */
    if (startWithLongest.length > 0 && startWithLongest[0]) {
        if (strgB.length() > strgA.length()) {
            strgA = stringB; 
            strgB = stringA;
        }
    }
    
    // Build the new blended string
    StringBuilder sb = new StringBuilder("");
    for (int i = 0; i < strgA.length(); i  ) {
        sb.append(strgA.charAt(i))
                /* 'Ternary Operator' is used here to ensure strgB 
                   contains the current index to carry on. If not
                   then just the remaining characters of strgA are 
                   sequentially apended to the StringBuilder object
                   to finish up things.                         */
                .append(i < strgB.length() ? strgB.charAt(i) : "");
    }
    
    return sb.toString();
}

CodePudding user response:

take two strings and use a method to alternate the characters. example - "test" "case" -> "tceasste"

private static String mixedUp(String first, String second)
{

First, identify the shorter string so it won't attempt to pull a character that is out out bounds

    int length = (first.length() > second.length()) 
        ? second.length() : first.length();

Then for that length, add their alternating characters to a new String() Object like so:

    String output = new String();
    for(int index = 0; index < length - 1; index  )
    {
        output  = first.charAt(index);
        output  = second.charAt(index);
    }

You can use substring to savely append the remainder of the Strings. Should the limit be out of bounds, no exception will be thrown, because substring will just return an empty String. - @thinkgruen

You can add the rest of the characters using the ternary operator again like so:

    output  = (first.length() > second.length()) 
        ? second.substring(length) : first.substring(length);
    return output;
}
  •  Tags:  
  • java
  • Related