Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get sub string after four spaces in the given string?

Tags:

java

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.

like image 622
Ram Avatar asked Feb 04 '13 12:02

Ram


3 Answers

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}", "");
like image 154
Adrián Avatar answered Sep 28 '22 05:09

Adrián


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.

like image 33
Mikhail Vladimirov Avatar answered Sep 28 '22 06:09

Mikhail Vladimirov


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);

}
like image 36
Achintya Jha Avatar answered Sep 28 '22 05:09

Achintya Jha