Search code examples
javastringbuilder

manipulating the strings to make new strings with the respective indexes


input :have anic eday

String[] words = sb.toString().split("//s");
    StringBuilder sbFinal = new StringBuilder();

    for(int i=0;i<words[0].length() ;i++){
        for(int j=0;j<words.length;j++){
            sbFinal.append(words[j].charAt(i));
        }
    }

    return sbFinal.toString() ;

output : have anic eday

I have a number of strings which I need to convert in the form where a new set of strings are printed ( space seperated ) which are formed by the respective chars of each strings given .

desired output : hae and via ecy

for example we have 3 words of 4 chars each , we want 4 words of 3 chars each .

have anic eday =>hae and via ecy

we pick 1st char from all 3 words to make the new first word .

I used the code shown above but it prints the input as output itself .


Solution

  • Although answered, I made up a more similar version to what you have originally designed, just with sysout instead of return, but change to your needs, or just adjust the .split() line:

    String sb = "have anic eday";
    String[] words = sb.split("\\s"); //you need to use BACKWARDSLASH "\\s" to get it to work.
    StringBuilder sbFinal = new StringBuilder();
    
    
    for (int i = 0; i < words[0].length(); i++) {
        for (int j = 0; j < words.length; j++) {
            sbFinal.append(words[j].charAt(i));
        }
        sbFinal.append(" ");
    }
    
    System.out.println(sbFinal.toString());
    

    You split with "//s", however " " or "\\s" seems to work perfectly fine.