String Manipulation Flashcards

1
Q

How do you reverse a string in Java?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you change a string to uppercase in Java?

A

Use the toUpperCase() method.

String str = “hello”;
String upper = str.toUpperCase();
System.out.println(upper); // Output: “HELLO”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How do you check if two strings are equal in Java?

A

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 well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

How do you find the length of a string in Java?

A

Use the length() method.

String str = “Hello”;
System.out.println(str.length());

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How do you extract a substring from a string in Java?

A

Use the substring() method.

String str = “Hello World”;
String sub = str.substring(0, 5); // Extract “Hello”
System.out.println(sub);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How do you get a character at a specific index in Java?

A

Use the charAt() method.

String str = “Hello”;
char c = str.charAt(1); // Gets ‘e’
System.out.println(c);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

How do you split a string by a delimiter in Java?

A

Use the split() method.

String str = “one,two,three”;
String[] parts = str.split(“,”);
System.out.println(Arrays.toString(parts));

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How do you concatenate two strings in Java?

A

Use the + operator or concat() method.

String s1 = “Hello”;
String s2 = “World”;
String result = s1 + “ “ + s2;
System.out.println(result); // Output: “Hello World”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you check if a string contains a specific substring?

A

Use the contains() method.

String str = “Hello World”;
System.out.println(str.contains(“World”)); // Output: true

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

How do you replace characters in a string in Java?

A

Use the replace() method.

String str = “hello”;
String replaced = str.replace(‘e’, ‘a’);
System.out.println(replaced);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly