Christopher Miller Christopher Miller - 1 month ago 6
Java Question

Creating a static method that meshes two strings together

We recently started learning about static methods and for this assignment we are making a "String Helper" program that creates a few static methods that modify strings, and this is the task for one of them:

meshStrings
: This method takes in two strings via parameters, meshes them together, and returns the meshed strings. Meshing alternates the each character in the first string with every character in the next string. If there are not enough characters to fully mesh then the rest will be appended to the end. For instance if the two strings were
"harp"
and
"fiddle"
the returned string will be
hfairdpdle
.

Here's the start of what I have, I don't have much:

public class StringHelper {
public static String meshStrings (String string1, String string2)
{

}


Driver class:

public class StringHelperTester {

public static void main (String[] args)
{
System.out.print(StringHelper.meshStrings("fiddle", "harp"));
}


I assume you'll have some type of for loop that prints out the
charAt
length of each string but I'm not exactly sure the best way to set it up. Help is appreciated.

Answer

the best way to enchance your skills is to just try ...

public static String meshStrings (String string1, String string2) {
        StringBuffer buff = new StringBuffer();
        int max = Math.max(string1.length(), string2.length());
        for(int i = 0; i < max; i++) {
            if(i < string1.length()) {
                buff.append(string1.charAt(i));
            }
            if(i < string2.length()) {
                buff.append(string2.charAt(i));
            }
        }
        return buff.toString();
    }

KISS : keep it simple and stupid. then you can enhance this code if you want, it's not optimal.

Comments