import java.util.Scanner;
public class StringBufferExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking string input
System.out.print("Enter a string: ");
String input = scanner.nextLine();
// Creating StringBuffer object
StringBuffer sb = new StringBuffer(input);
// Deleting a part of the string using delete(start, end)
System.out.print("Enter start index to delete: ");
int start = scanner.nextInt();
System.out.print("Enter end index to delete (exclusive): ");
int end = scanner.nextInt();
if (start >= 0 && end <= sb.length() && start < end) {
sb.delete(start, end);
System.out.println("After deleting from index " + start + " to " + (end - 1) + ": " + sb);
} else {
System.out.println("Invalid indexes. Skipping delete operation.");
}
scanner.nextLine(); // consume newline
// Removing specific character
System.out.print("Enter a character to remove: ");
char ch = scanner.nextLine().charAt(0);
for (int i = 0; i < sb.length(); i++) {
if (sb.charAt(i) == ch) {
sb.deleteCharAt(i);
i--; // Move back to recheck the new character at current position
}
}
System.out.println("After removing character '" + ch + "': " + sb);
scanner.close();
}
}
Comments
Post a Comment