In java how to get substring from a string till a character c?
To get a substring from a string in Java up until a certain character, you can use the indexOf
method to find the index of the character and then use the substring
method to extract the substring.
Here is an example of how you can do this:
String s = "Hello, world!";
char c = 'w';
int index = s.indexOf(c);
if (index != -1) {
String sub = s.substring(0, index);
System.out.println(sub); // Outputs "Hello, "
}
The indexOf
method returns the index of the first occurrence of the specified character in the string. If the character is not found, it returns -1
.
The substring
method extracts a portion of the string and returns it as a new string. The first argument is the starting index of the substring, and the second argument is the ending index (exclusive).
I hope this helps! Let me know if you have any other questions.