user1657423
user1657423

Reputation: 11

How to use indexOf (int ch) in java

I am trying to get the index number of a character in a string to divide the string into substrings. Example: I want to turn:

String book1 = "green eggs and ham, usa, dr. seuss";

into:

green eggs and ham
usa
dr. seuss

This has to work for strings of different lengths. Basically, if I used different words it would still work.

I need help understanding the indexOf() method to get the index of the commas to put into a substring.

I have tried using variables in the method call after the indexOf, and I get errors when I use anything other than an int.

Upvotes: 1

Views: 1671

Answers (3)

Sujay
Sujay

Reputation: 6783

I am not so sure of your actual requirement but you have quite a few options to try out:

  • Use split(String) method to split the string and store it as an array of String
  • Use StringTokenizer to tokenize your String on a particular delimiter and use nextToken() to get the tokens. (Note that StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code)
  • Third option would be to use regular expressions using Pattern

Choose which ever is applicable to your requirement.

Upvotes: 5

Code-Apprentice
Code-Apprentice

Reputation: 83537

If you are allowed to use it, the split() method is exactly what you need.

Otherwise, if you are required to only use indexOf(), look at the Java API documentation for String API to understand how it works. The first thing I notice is that there are three different versions of indexOf(): indexOf(int), indexOf(int, int), and indexOf(String). I believe the second of these will be the most applicable to this problem. Since the documentation states that this version of indexOf() "returns the index within this string of the first occurrence of the specified character, starting the search at the specified index," you will most likely need a loop of some kind in order to find every occurrence of a character.

Upvotes: 0

davidmontoyago
davidmontoyago

Reputation: 1833

Use split.

"green eggs and ham, usa, dr. seuss".split(", ");

See: String.split

Upvotes: 3

Related Questions