I have a String "Magic Word". I need to trim the string to extract "Magic" only. I am doing the following code.
String sentence = "Magic Word"; String[] words = sentence.split(" "); for (String word : words) { System.out.println(word); }
I need only the first word. Is there any other methods to trim a string to get first word only if space
occurs?
FIND returns the position (as a number) of the first occurrence of a space character in the text. This position, minus one, is fed into the LEFT function as num_chars. The LEFT function then extracts characters starting at the the left side of the text, up to (position - 1).
To get first character from String in Java, use String. charAt() method. Call charAt() method on the string and pass zero 0 as argument. charAt(0) returns the first character from this string.
The Java String replaceFirst() method replaces the first substring 'regex' found that matches the given argument substring (or regular expression) with the given replacement substring. The substring matching process start from beginning of the string (index 0).
String firstWord = "Magic Word"; if(firstWord.contains(" ")){ firstWord= firstWord.substring(0, firstWord.indexOf(" ")); System.out.println(firstWord); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With