JAVA : Different ways to manipulate strings in Java?
SDET Automation Testing Interview Questions & Answers
We will be covering a wide range of topics including QA manual testing, automation testing, Selenium, Java, Jenkins, Cucumber, Maven, and various testing frameworks.
JAVA : Different ways to manipulate strings in Java?
In Java, there are several ways to manipulate strings. Here are some common ways to perform string manipulation in Java:
1. Concatenation: You can concatenate two or more strings using the `+` operator or the `concat()` method. For example:
String str1 = "Hello";
String str2 = "World";
String result = str1 + " " + str2;
// or
String result = str1.concat(" ").concat(str2);
2. Substring Extraction: You can extract a substring from a string using the `substring()` method. This allows you to obtain a portion of the original string based on the specified start and end indices. For example:
String str = "Hello, World!";
String substr = str.substring(7, 12); // Extracts "World"
3. Case Conversion: You can convert the case of a string using the `toUpperCase()` and `toLowerCase()` methods. These methods return a new string with the converted case. For example:
String str = "Hello, World!";
String uppercase = str.toUpperCase(); // "HELLO, WORLD!"
String lowercase = str.toLowerCase(); // "hello, world!"
4. Replacing Characters or Substrings: You can replace characters or substrings within a string using the `replace()` method. This allows you to substitute specific characters or patterns with desired values. For example:
String str = "Hello, World!";
String replaced = str.replace("Hello", "Hi"); // "Hi, World!"
5. Splitting: You can split a string into an array of substrings using the `split()` method. This is useful when you want to break a string based on a delimiter. For example:
String str = "Hello,World,Java";
String[] splitArray = str.split(","); // ["Hello", "World", "Java"]
6. Trimming Whitespace: You can remove leading and trailing whitespace from a string using the `trim()` method. This is helpful when you want to eliminate unnecessary spaces. For example:
String str = " Hello, World! ";
String trimmed = str.trim(); // "Hello, World!"
7. Checking String Length: You can get the length of a string using the `length()` method. It returns the number of characters in the string. For example:
String str = "Hello, World!";
int length = str.length(); // 13
These are some of the common ways to manipulate strings in Java. Additionally, the `StringBuilder` and `StringBuffer` classes provide more advanced string manipulation capabilities, such as efficient string concatenation or inserting values at specific positions.