简体   繁体   中英

How to recursively split a string in half and then split the smaller strings in Java

on my recent midterm I had a question where I was told to split a big string into 2 equal small and split the smaller strings into halves again. I know it has to be done recursively for this question but I am not aware of how to apply it to Java code.

Any help would be great, Thank you.

public class Question7a {

public static void main(String[] args) {
    String strings = "aaaa bbbb cccc dddd";
    Question7a question7a = new Question7a();
    question7a.splitString(strings);
}

public void splitString(String words){
        int m = words.length() / 2; //gets the middle length of the string to split there.
        for (int i=0; i < m; i++) {
        String[] halves = {words.substring(0, m), words.substring(m)};
        System.out.println(halves[0]); //first half of the string
        System.out.println(halves[1]); //second part
            if(halves[0].equals(true)){
                int m2 = halves.length/2; //Intent was to get the middle of the new half.
                halves[0] = {hal.substring(0, m2), words.substring(m2)};
                halves[1] = {words.substring(0, m2), words.substring(m2)};
                System.out.println(halves[0]);
                System.out.println(halves[1]);
            }
            else{
                System.out.println("Null");
    }
}

}

Kind of want a output to something like:

"aaaa bbbb"      cccc  dddd
   |                |
   |                |
"aaaa" "bbbb"    cccc  dddd
   |      |
   |      |  
"aa" "aa" "bb" "bb"

and similar (not sure if this is the right way to look at it) for the other half.

Try this:

import java.util.Stack;
class Hackerearth{
    public static void main(String args[] ) throws Exception {
        Stack<String> st = new Stack<>();
        String str = "aaaa bbbb cccc dddd";
        st.push(str);
        split(st);
    }

    public static void split(Stack<String> st){
        while(!st.empty()){
            String s = st.pop();
            if(s.length() == 1){
                System.out.println(s);
            }
            else{
                int mid = s.length() / 2;
                String first = s.substring(0, mid);
                String second = s.substring(mid, s.length());
                st.push(second);
                st.push(first);
            }
        }
    }
}

You can use Stack in Java.util package.. It has push and pop methods predefined to add and remove items.. Stack Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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