How to reverse each word of a string based on the input digit given?

Viewed 157

Following are the rules which must be followed by the program:

  1. Every word in the string must be divided upto n letters each and reverse them from the start
  2. Only those words must be reversed which are having length equal or greater than n

For example, if string = "law of attraction" and input n = 3. Here, the length of of is less than n, thus must not be reversed, but law and attraction are having length greater than or equal to 3 thus must be reversed as

law as wal and attraction as ttacaroitn

Final output: wal of ttacaroitn

In my given code, i can only able to reverse the string, but not words based on the input digit. Not getting any idea.

    Scanner sc = new Scanner(System.in);
    String str = sc.nextLine();
    System.out.println("Enter String: "+str);
    
    Scanner sc1 = new Scanner(System.in);
    int Digit = sc.nextInt();
    
    int count = str.split("\\s+").length;
    System.out.println("No.of words: "+count);
    System.out.println("Given string: "+str);
    if(Digit<=count) {
        String s[] = str.split(" ");
        String ans = "";
        for (String part : str.split(" ")) {
            System.out.print(new StringBuilder(part).reverse().toString());
            System.out.print(" ");
        }
    }   
    else {
        System.out.println("Your input Digit is Greater than count of words.");
    }
2 Answers

The method reverseSubString will split the word after every n characters. It is then reversed.

public static void main(String[] args){
  String line = "law of attraction";
  int n = 3;
  String[] words = line.split(" ");
  for(String word: words){
    if(word.length()>=n){
      System.out.print(reverseSubString(word, n)+" ");
    } else {
      System.out.print(word + " ");
    }
  }
}

public static String reverseSubString(String s, int n) {
  String ans = "";
  String[] substrings = s.split("(?<=\\G.{"+n+"})");
  for(String substring : substrings){
    if(substring.length()==n)
       ans += new StringBuffer(substring).reverse().toString();
    else
       ans += substring;
  }
  return ans;
}

OUTPUT

wal of ttacaroitn

You are using if(Digit<=count) which means if n is less than the number of words then reverse all words in the loop which is the problem.

   if(Digit<=count) {
        String s[] = str.split(" ");
        String ans = "";
        for (String part : str.split(" ")) {
            System.out.print(new StringBuilder(part).reverse().toString());
            System.out.print(" ");
        }
    }

You should check with the length of every word after splitting inside loop and do the reverse when greater than or equal to n.

    String s[] = str.split(" ");
    for (String part : s) {
        // here to check
        if(part.size() >= Digit){
            part = new StringBuilder(part).reverse().toString();
        }
        System.out.print(part);
        System.out.print(" ");
    }
Related