the below code input o1ps will return oops but o2ps should return ooops is there any way we can execute o2ps has ooops

Viewed 50
package adc;
import java.util.*;
public class bca {
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the sentence to decrypt");
String s=sc.nextLine();
char[] ans = s.toCharArray();
int len=s.length();
char[] sol= new char[len];
System.out.println("len="+s.length());
for(int i=0;i<len;i++) {
    int j=i;
    if(ans[i]=='1') {
        sol[i]=ans[i-1];
    }
    else if(ans[i]=='2') {
        sol[i]=ans[i-1];
        sol[i+1]=ans[i-1];
        
        
    }
    else {
        sol[i]=ans[i];
    }
    System.out.print(sol[i]);
    }
  sc.close();
    
  }
  }

new here learning java tring to get some help here thank you.

Enter the sentence to decrypt Input:o1ps o2ps output:len=9 oops oopsis it possible to make o2ps has ooops

1 Answers

You need different counters for the input string and the output string, however, as you don't know in advance the length of the output string, you can use a StringBuilder:

    char[] ans = s.toCharArray();
    StringBuilder out = new StringBuilder();
    System.out.println("len=" + s.length());
    for (int i = 0; i < ans.length; i++) {
        if (i > 0 && ans[i] >= '0' && ans[i] <= '9') {
            char prev = ans[i-1];
            int count = ans[i] - '0';
            for (int j = 0; j < count; ++j) {
                out.append(prev);
            }
        } else {
            out.append(ans[i]);
        }
    }
    System.out.println("output=" + out);

UPDATE:

To also reverse words:

    char[] ans = s.toCharArray();
    List<String> words = new ArrayList<>();
    StringBuilder out = new StringBuilder();
    System.out.println("len=" + s.length());
    for (int i = 0; i < ans.length; i++) {
        if (ans[i] == ' ') {
            if (out.length() > 0) {
                words.add(out.toString());
                out.setLength(0);
            }
        } else if (i > 0 && ans[i] >= '0' && ans[i] <= '9') {
            char prev = ans[i-1];
            int count = ans[i] - '0';
            for (int j = 0; j < count; ++j) {
                out.append(prev);
            }
        } else {
            out.append(ans[i]);
        }
    }
    if (out.length() > 0) {
        words.add(out.toString());
    }
    Collections.reverse(words);
    String output = words.stream().collect(Collectors.joining(" "));
    System.out.println("output=" + output);
Related