Home > Net >  Find all substrings
Find all substrings

Time:04-26

Basically I am trying to get my code to print all substrings of a input. If the input is rum it would go as r u m ru um rum. I am not very good with nested loops and so far the out put I get is rr uu mm. I would appreciate if anyone can help me understand what I'm doing wrong here.

import java.util.Scanner;
    
public class NestedLoop {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();
        
        for(int i = 0; i < s.length(); i  ) {
            char cur = s.charAt(i);
            for (int j = 1; j < s.length(); j   ) {
                char cu = s.charAt(j);
                System.out.println(cur);
            }
        }
    }
}

CodePudding user response:

May this can help you.

You will end up in 2^(String length) combinations as your final output including the empty string. You can avoid it by starting the outer loop from 1 instead of 0. The outer loop is counting possible outputs and inter loop in bit counter with a upper limit as a length of the string. Based on bit set for j in binary the corresponding character is selected.

public static List<String> findSubstrings(String str) {
    int charCount = str.length();
    int powSize = (int)Math.pow(2, charCount);
    List<String> result = new ArrayList<>();

    for (int i = 0; i < powSize; i  ) {
      StringBuilder sb = new StringBuilder();
      for (int j = 0; j < charCount; j  ) {
        if ((i & (1 << j)) != 0) {
          sb.append(str.charAt(j));
        }
      }
      result.add(sb.toString());
    }

    return result;
}

CodePudding user response:

The second pointer should start from 1 plus the outer loop . To print the string you can use the substring function which includes the element at the starting index and excludes the element at the end index.

public class Nestedloop {
    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);
        String s = scan.nextLine();

        for (int i = 0; i < s.length(); i  ) {
            for (int j = i   1; j <= s.length(); j  ) {
                System.out.println(s.substring(i, j));
            }
        }
    }
}

and the output for rum is

r
ru
rum
u
um
m
  • Related