简体   繁体   中英

How do I get the 5th word in a string? Java

Say I have a string of a text document and I want to save the 124th word of that string in another string how would I do this? I assume it counts each "word" as a string of text in between spaces (including things like - hyphens).

Edit: Basically what I'm doing right now is grabbing text off a webpage and I want to get number values next to a certain word. Like here is the webpage, and its saved in a string .....health 78 mana 32..... or something of the sort and i want to get the 78 and the 32 and save it as a variable

If you have a string

String s = "...";

then you can get the word (separated by spaces) in the n th position using split(delimiter) which returns an array String[] :

String word = s.split("\\s+")[n-1];

Note:

  • The argument passed to split() is the delimiter. In this case, "\\\\s+" is a regular expression , that means that the method will split the string on each whitespace, even if there are more than one together.

Why not convert the String to a String array using StringName.split(" "), ie split the string based on spaces. Then only a matter of retrieving the 124th element of the array.

For example, you have a string like this:

String a="Hello stackoverflow i am Gratin";

To see 5th word, just write that code:

   System.out.println(a.split("\\s+")[4]);

This is a different approach that automatically returns a blank String if there isn't a 5th word:

String word = input.replaceAll("^\\s*(\\S+\\s+){4}(\\S+)?.*", "$1");

Solutions that rely on split() would need an extra step of checking the resulting array length to prevent getting an ArrayIndexOutOfBoundsException if there are less than 5 words.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM