简体   繁体   English

在Java中使用indexOf

[英]Using indexOf in Java

I am trying to use indexOf(" "); 我正在尝试使用indexOf(“”); on this string 在这个字符串上

"This i$ an aardvaAr yeEeeAs onDo qwerty XYZ9";

this is my code 这是我的代码

        space = word.indexOf(" ");

        tempWord = word.substring(0, space);

Now I get what I want which is This string but now how do I get the next space which has this after it: i$ , and the next one unitl the end of the string? 现在,我得到的是This字符串,但是现在,我如何获得下一个在其后有空格的空间: i$和下一个unitl字符串的末尾?

* EDIT * 编辑

Please no arrays for this question 请没有这个问题的数组

Use the overload of indexOf which takes the starting index too: 使用indexOf重载,重载也需要起始索引:

int nextSpace = word.indexOf(" ", space + 1);

(Although there may very well be a better approach to your bigger problem.) (尽管很可能有更好的方法来解决更大的问题。)

if you don't want to split the string (and create an String array) you can read the rest of the string after hitting the first space (btw. this seems like a schoolwork on recursive functions): 如果您不想拆分字符串(并创建一个String数组),则可以在碰到第一个空格后读取字符串的其余部分(顺便说一句,这似乎是递归函数的功课):

int space = test.indexOf(" ");
String before = test.substring(0, space);
String after = test.substring(space + 1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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