I want to keep all the characters before a space and remove the rest of the string.
Example:
String str = "Davenport FL 33897 US";
I want to print only "Davenport" and remove the rest of the string. Also the string is dynamic every time.
I want to keep all the characters before a space and remove the rest of the string.
Example:
String str = "Davenport FL 33897 US";
I want to print only "Davenport" and remove the rest of the string. Also the string is dynamic every time.
You need to use substr
and indexOf
str.substr(0,str.indexOf(' ')); // "Davenport"
substr(0,X)
will give you the sub string of your string starting at index 0 and ending at index X
,
Because you want to get the first word until the first space you replace X
with:
str.indexOf(' ')
which returns the index of the first space in your string
We can use regular expression to detect space and special character. You can utilize below code to do the same.
String str="Davenport FL 33897 US";
String[] terms = str.split("[\\s@&.?$+-]+");
System.out.println(terms[0]);
It's working for me.
You can use the split function to split the string using ' ' as your delimeter.
const myString = "Davenport FL 33897 US"
const splitString = myString.split(' ')
split() returns an array of strings that separated using the delimeter. you can just get the index of the first string by.
console.log(splitString[0])
another way would be just to put the index after the split function so that you get only what you want and not the full array.
const firstWord = myString.split(' ')[0]
String[] newOutput = str.split(" ");
String firstPart = newOutput[0];