String Manipulation Flashcards
How do you reverse a string in Java?
Use StringBuilder and its reverse() method.
String str = “Hello”;
String reversed = new StringBuilder(str).reverse().toString();
System.out.println(reversed);
String reversed;
or for (int i =0; i<str.length() ;i++){
reversed = reversed + str.charAt(i);
}
How do you change a string to uppercase in Java?
Use the toUpperCase() method.
String str = “hello”;
String upper = str.toUpperCase();
System.out.println(upper); // Output: “HELLO”
How do you check if two strings are equal in Java?
How do you check if two strings are equal in Java?
A: Use the equals() method.
String s1 = “hello”;
String s2 = “hello”;
System.out.println(s1.equals(s2)); // Output: true
How do you find the length of a string in Java?
Use the length() method.
String str = “Hello”;
System.out.println(str.length());
How do you extract a substring from a string in Java?
Use the substring() method.
String str = “Hello World”;
String sub = str.substring(0, 5); // Extract “Hello”
System.out.println(sub);
How do you get a character at a specific index in Java?
Use the charAt() method.
String str = “Hello”;
char c = str.charAt(1); // Gets ‘e’
System.out.println(c);
How do you split a string by a delimiter in Java?
Use the split() method.
String str = “one,two,three”;
String[] parts = str.split(“,”);
System.out.println(Arrays.toString(parts));
How do you concatenate two strings in Java?
Use the + operator or concat() method.
String s1 = “Hello”;
String s2 = “World”;
String result = s1 + “ “ + s2;
System.out.println(result); // Output: “Hello World”
How do you check if a string contains a specific substring?
Use the contains() method.
String str = “Hello World”;
System.out.println(str.contains(“World”)); // Output: true
How do you replace characters in a string in Java?
Use the replace() method.
String str = “hello”;
String replaced = str.replace(‘e’, ‘a’);
System.out.println(replaced);