Reputation: 11
I want to check if a String of groceries contain any words related to junk food (e.g. 'chocolate', 'candy', 'crisps') and then I want to change these words to fruits/vegetables.
How can I use the substring/indexOf methods without knowing the location of the words, as it will be user input.
Thanks.
Upvotes: 0
Views: 96
Reputation: 435
So it is not a "String array", plz edit this. i have to guess your code ?
String s = "potato, chocolate, strawberrie"
s.replace("chocolate", "apple");
You can still do it with substring if u want to train yourself. http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
You will need :
String choco = "chocolate";
int pos = s.indexOf(choco); //returns 8
int size = choco.length;
s = s.substring(0, pos) + "apple" + s.substring(pos+size, s.length);
Here is everything u need :)
Upvotes: 1
Reputation: 43
I don't think substring is a "good" way to do this as if you look at the API for String, there isn't a substring method that takes parameters other than indices of characters in the string. But you will still need substring!
Assuming you still want to do this in a manner where you dump the array into a string, a more suitable method of the String API would be indexOf(). The parameter is the string you want to look for and the method will return the index of the first occurrence or a -1 if it is not found. Once you have the initial index of the string from indexOf(), then you can use substring to get the string. For the second parameter in the substring method, the end index, you can just add the length of the String you're looking for, minus 1, to the start index.
If you want to do this from a more object oriented approach, I recommend creating an object for each String and then you can customize that class of object to have a parameter holding what type of item the String is. Then, using the comparator, you can iterate through the array finding types of items. I provided an in depth answer on how to do this in this question.
Give one of these a shot and if you're still stuck or having difficulties, comment on my answer and I can add an edit with some code. But it's important that you try first!
Upvotes: 0
Reputation: 351
What you really want to do is iterate on the array and verifiy if each value of the array contais a mention to a junk food; the method contains is more appropiate for that.
boolean junkFoodValidator(String[] array) { for (String a : array{ if(a.contains("chocolate") || a.contains("candy") { //you can add more validados here return true; } } return false; }
Upvotes: 0
Reputation: 62129
You can always use String.replace()
, but if you must use String.substring()
, then the way it is usually done is as follows:
String junk = "chocolate";
String food = "some chocolate bar";
int index = food.indexOf( junk );
if( index != -1 )
{
int n = index + junk.length();
food = food.substring( 0, index ) + "banana" + food.substring( n );
}
System.out.println( food );
Upvotes: 1