Untitled
unknown
plain_text
a year ago
4.2 kB
6
Indexable
import java.util.Scanner;
public class StringMethodsDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
boolean continueProgram = true;
while (continueProgram) {
System.out.println("Enter a string:");
String input = scanner.nextLine();
System.out.println("Choose an operation:");
System.out.println("1. Convert to Uppercase");
System.out.println("2. Convert to Lowercase");
System.out.println("3. Find character at a specific index");
System.out.println("4. Check if the string contains a substring");
System.out.println("5. Compare with another string");
System.out.println("6. Trim the string");
System.out.println("7. Get the length of the string");
System.out.println("8. Replace characters in the string");
System.out.println("9. Split the string by space");
int choice = scanner.nextInt();
scanner.nextLine(); // consume the newline after the number
switch (choice) {
case 1:
System.out.println("Uppercase: " + input.toUpperCase());
break;
case 2:
System.out.println("Lowercase: " + input.toLowerCase());
break;
case 3:
System.out.println("Enter index:");
int index = scanner.nextInt();
if (index >= 0 && index < input.length()) {
System.out.println("Character at index " + index + ": " + input.charAt(index));
} else {
System.out.println("Invalid index.");
}
scanner.nextLine(); // consume newline
break;
case 4:
System.out.println("Enter substring to check:");
String substring = scanner.nextLine();
if (input.contains(substring)) {
System.out.println("The string contains the substring.");
} else {
System.out.println("The string does not contain the substring.");
}
break;
case 5:
System.out.println("Enter another string to compare:");
String anotherString = scanner.nextLine();
if (input.equals(anotherString)) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are not equal.");
}
break;
case 6:
System.out.println("Trimmed string: " + input.trim());
break;
case 7:
System.out.println("Length of the string: " + input.length());
break;
case 8:
System.out.println("Enter character to replace:");
String oldChar = scanner.nextLine();
System.out.println("Enter new character:");
String newChar = scanner.nextLine();
System.out.println("Updated string: " + input.replace(oldChar, newChar));
break;
case 9:
String[] words = input.split(" ");
System.out.println("Split words:");
for (String word : words) {
System.out.println(word);
}
break;
default:
System.out.println("Invalid choice.");
break;
}
System.out.println("Do you want to perform another operation? (yes/no)");
String continueResponse = scanner.nextLine();
if (!continueResponse.equalsIgnoreCase("yes")) {
continueProgram = false;
}
}
scanner.close();
System.out.println("Program terminated.");
}
}
Editor is loading...
Leave a Comment