Write a java program for Simple String Manipulation.

Write a program to read a string and return a modified string based on the following rules.

Return the String without the first 2 chars except when:

  1. Keep the first char if it is ‘j’.
  2. Keep the second char if it is ‘b’.

The return type (string) should be the modified string based on the above rules. Consider all letters in the input to be the small case.

Input and Output Format

  • Input consists of a string with a maximum size of 100 characters.
  • The output consists of a string.

Refer sample output for formatting specifications

Sample Input 1:

hello

Sample Output 1:

llo

Sample Input 2:

java

Sample Output 2:

Jva

Simple String Manipulation in Java

Following are the steps to manipulate string in Java:

  • Input string from the user. Pass it to display() method.
  • Inside the method, first, create an empty string buffer to hold the updated string.
  • Now, get the first and second characters from the string.
    • check if the first character is not ‘j’ and the second character is not ‘b‘ then append the substring from 2nd index to string buffer.
    • Else if, the first character is ‘j’ and the second character is not  ‘b’ then append the substring from the 2nd index to string buffer.
    • Else if, the first character is not  ‘j’ and the second character is  ‘b‘ then append the substring from the 1st index to string buffer.
    • Otherwise, append the whole string to the string buffer.
  • At last, return the string representation of the value in the string buffer.
import java.util.Scanner;

public class Main {
  public static void main(String args[]) {
    Scanner sc = new Scanner(System.in);
    String s = sc.nextLine();
    System.out.println(display(s));

  }

  public static String display(String s) {
    StringBuffer sb = new StringBuffer();
    char a = s.charAt(0);
    char b = s.charAt(1);
    if (a != 'j' && b != 'b')
      sb.append(s.substring(2));
    else if (a == 'j' && b != 'b')
      sb.append("j").append(s.substring(2));
    else if (a != 'j' && b == 'b')
      sb.append(s.substring(1));
    else
      sb.append(s.substring(0));
    return sb.toString();
  }

}

Output

Thus, in this way, we learn how to manipulate strings in Java.