I have string like "align is going to school sad may me"
. I want to get the sub string after the four spaces. The String will be entered at run time. can anyone suggest me to find the Sub String after some set of spaces......
String st = "align is going to school sad may me";
int i = 0;
String [] strings = new String [15];
StringTokenizer stringTokenizer = new StringTokenizer (st, " ");
while (stringTokenizer.hasMoreElements ())
{
strings [i]= (String)stringTokenizer.nextElement ();
i++;
}
System.out.println ("I value is" + i);
for (int j=4; j<i; j++)
{
System.out.print (strings[j] + " ");
}
I've tried this one and it's working can you please suggest me simple method to find the Sub string after some set of spaces.
st = st.replaceAll("^(\\S*\\s){4}", "");
^
indicates that we remove only from the first character of the string.
\s
is any white space. It would also remove, for example, tabulations.
\S
is any non white space character.
*
means any number of occurrences of the character.
So, \S*
is any number of non white space characters before the white space.
{4}
is obviously because you want to remove 4 white spaces.
You could also use:
st = st.replaceFirst("(\\S*\\s){4}", "");
which is the same but you don't need the ^
.
In case the input string could have less than 4 white spaces:
st = st.replaceAll("^(\\S*\\s){1,4}", "");
would return you the last word of the string, only if the string doesn't end on a white space. You can be sure of that if you call trim
first:
st = st.trim().replaceAll("^(\\S*\\s){1,4}", "");
What about using split?
st.split (" ", 5) [4]
It splits string by spaces, into not more than 5 chunks. Last chunk (with index 4) will contain everything after fourth space.
If it is not guaranteed that string contains 4 spaces, additional check is required:
String [] chunks = st.split (" ", 5);
String tail = chunks.length == 5 ? chunks [4] : null;
Tail will contain everything after fourth space or null, is there are less than four spaces in original string.
public static void main(String[] args) {
String st = " align is going to school sad may me ";
String trim = st.trim(); // if given string have space before and after string.
String[] splitted = trim.split("\\s+");// split the string into words.
String substring = "";
if (splitted.length >= 4) { // checks the condition
for (int i = 4; i < splitted.length; i++)
substring = substring + splitted[i] + " ";
}
System.out.println(substring);
}
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