Hey everyone, I am very new to Java and I am learning how to change a specific word from a line of text that is inputted by the user. For example, if I created the program to change the word "hate" to the word "love" (which is what the program is doing) how can I make the program i created more efficient?
This is the main portion of my program...
NOTE: I feel like there should be a way to do this program without having to create a seperate String called subsection. Thanks for the help, it is greatly appreciated!
String sentence, subsentence;
Scanner keyboard = new Scanner(System.in);
System.out.println("Please enter a line of text.");
System.out.println("I will change the word hate to the word
sentence = keyboard.nextLine();
subsentence = sentence;
System.out.println("I am now checking to see if \"hate\" is in
System.out.println(sentence + " is now changed to");
position = subsentence.indexOf("hate ");
subsentence = subsentence.substring(0, position) + "love";
position = position + 4;
sentence = sentence.substring(position);
System.out.println(subsentence + sentence);
Before that, if user enter a value "hate" how your program detect it? Then how you match the relevant response?
Or you just want to replace the word "hate" with "love"?
Yes, I just want to replace the word "hate" with "love". Before I added the second String (subsentence), The program would still replace "hate" with "love" but it would stop the sentence right there. So if I had "I hate this program" it would only show up as "I love" and not finish the rest of the sentence
Read the String API. There is a method call replaceAll, where you can replace words/letters, in a single line.
The way you tried is too complex. Give a try and let me know if you stuck with.
use the String method replace() or replaceAll() to replace text.
Better to use replaceAll, because of regex could use.
Ok great, thanks guys. I'll give it a shot and see if it works. You guys must be tired of all of these questions like this, hopefully one day i'll help you guys out!
It's really nice. Try to takeout the best, and give back more than that.
Originally Posted by melovehockey