What is the method for extracting a substring in Java?
There are several methods for string truncation in Java.
- You can use the `substring()` method to extract a portion of a string by specifying the starting and ending indexes. For example, with the string “Hello World”, `str.substring(6, 11)` would give you “World”.
- With the split() method, you can divide a string into multiple substrings by specifying a delimiter, and it will return an array of strings. For example, if we have a string “Hello,World” and use str.split(“,”), we will get an array with two elements, “Hello” and “World”.
- Combining the use of the substring() and indexOf() methods allows you to find the position of a specific character or string with indexOf() and then extract a portion of the string with substring(). For example, in the string “Hello World”, you can find the index of “World” using indexOf() and then extract that portion of the string using substring().
- Utilizing the StringTokenizer class: The StringTokenizer class is a tool class used to divide a string into multiple substrings by specifying a delimiter. For example: String str = “Hello, World”; StringTokenizer tokenizer = new StringTokenizer(str, “, “); while (tokenizer.hasMoreTokens()) { String substr = tokenizer.nextToken(); // substr will be “Hello” and “World” in sequence }
These methods can be used according to specific needs, selecting the most suitable method for truncating strings.