2

I am trying to use 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?

*EDIT

Please no arrays for this question

6
  • 2
    It would be better to split the String using String[] substringsNoSpace = word.split(" "); Commented Jan 21, 2013 at 20:32
  • I am sorry I forgot to mention, I cant use arrays Commented Jan 21, 2013 at 20:34
  • 1
    Any other limitation for the solution? Could you use java.util.Scanner or java.util.regex.Pattern or just String class methods? Commented Jan 21, 2013 at 20:39
  • This has to look like a first year project, so it better to keep it simple Commented Jan 21, 2013 at 20:43
  • java.util.Scanner is for first year project, so it's up to you indeed. Also, you can always add results of further investigation to your project only if you demonstrate that you understand the proposed solution :). Commented Jan 21, 2013 at 20:45

2 Answers 2

6

Use the overload of indexOf which takes the starting index too:

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

(Although there may very well be a better approach to your bigger problem.)

Sign up to request clarification or add additional context in comments.

1 Comment

That is what I like, an nice quick answer :)
0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.