In: Computer Science
I need to write java program that do replace first, last, and remove nth character that user wants by only length, concat, charAt, substring, and equals (or equalsIgnoreCase) methods.
No replace, replaceFirst, last, remove, and indexOf methods and letter case is sensitive.
if user's input was "be be be" and replace first 'b'
replace first should do "e be be"
replace last should do "be be e"
remove nth character such as if user want to remove 2nd b
it should be like "be e be"
Solution:
import java.util.Scanner; public class Replace { public static void main(String[] args) { String input; String first = "", last = "", n = "", x; int choice, i, index, count = 0; Scanner in = new Scanner(System.in); System.out.print("Enter a string:"); input = in.nextLine(); while (true) { System.out.print("\n1.Replace First\n2.Replace Last\n3.Replace nth\n4.Exit\n"); System.out.print("Enter your choice:"); choice = in.nextInt(); switch (choice) { case 1: System.out.print("Enter the character whose first occurrence has to be replaced:"); x = in.next(); for (i = 0; i < input.length(); i++) { if (input.charAt(i) == x.charAt(0)) { first = input.substring(0, i) + input.substring(i + 1); break; } } System.out.print("Result is " + first); break; case 2: System.out.print("Enter the character whose last occurrence has to be replaced:"); x = in.next(); for (i = input.length() - 1; i >= 0; i--) { if (input.charAt(i) == x.charAt(0)) { last = input.substring(0, i) + input.substring(i + 1); break; } } System.out.print("Result is " + last); break; case 3: System.out.print("Enter the character whose nth occurrence has to be replaced:"); x = in.next(); System.out.print("Enter the value of n:"); index = in.nextInt(); for (i = 0; i < input.length(); i++) { if (input.charAt(i) == x.charAt(0)) count++; if (count == index) break; } n = input.substring(0, i) + input.substring(i + 1); System.out.print("Result is " + n); break; case 4: System.out.print("Bye\n"); System.exit(0); } } } }
Output: