So basically what I need help I need help doing is removing a word from a sting. I dont know how to use array, char and such just for those who refer me to that.
Output Ex:
Enter a sentence: I really like Jolly Ranchers.
Enter a string: really
I like Jolly Ranchers.
I just need to remove every occurrence of the string from the sentence essentially. Thanks for help in advance!
(Not looking for a handout, perhaps pseudocode or another example.)
Use replaceAll function,
this function gets two params
regex - the string you want to replace
substr- the string to replace it with
example:
newString = str1.replaceAll(regex, substr);
newString is the edited string
str1 is the string you wish to edit
String.replaceAll works for that
package se.samples;
import java.util.Scanner;
public class WordRemover {
static final String welcomeMessage = "Enter a sentence: ",
secondMessage = "Enter a string: ",
resultMessage = "";
static String replace(String source, String that){
return source.replaceAll(that, "");
}
public static void main(String[] args) throws Exception {
System.out.print(welcomeMessage);
try(Scanner s = new Scanner(System.in)){
String input = s.nextLine();
System.out.print(secondMessage);
System.out.println(resultMessage + replace(input, s.nextLine()));
}
}
}
You can go this way :
public static String remove(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence :");
String sentence = sc .nextLine();
System.out.println("Enter a word :");
String word = sc .nextLine();
String res ="";
for(String words : sentence.split(" ")){
if(!words.equalsIgnoreCase(word)){ //or words!=word if you want to NOT ignore the case
res+=words+" ";
}
}
return res;
}
public static void main(String[] args) {
System.out.println(remove());
}
It looks every word, and keep only the ones who are not equals to the word you enter
Or a more with a more shorter way :
public static String remove(){
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence :");
String sentence = sc .nextLine();
System.out.println("Enter a word :");
String word = sc .nextLine();
return sentence.replaceAll(word,"");
}
Please try this
String[] s = originalString.split(" ");
String wordToRemove = StandardInput;
String finalString ="";
for(String word : s){
if(!word.equals(wordToRemove )){
System.out.Print(word);
finalString += word+" ";
}
}
I believe strings have a replace method so try something like str.replace("really", "") or replaceEach if there will be more than one. I suggest looking at the Java API for more functions.
Related
In this code, I am trying to replace a letter from a String entered by a user. For example, the program asks for a word, and the user enters "hello", the next variable that the user inputs is the letter that is going to be replaced ("l"), and the final variable is the letter that is going to replace the previous variable ("x").
The result should be "hexxo", but my program is only replacing one of the l's, what is wrong with my program?
import java.util.Scanner;
public class Letter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println("\nEnter the letter you want to replace:");
String replace = input.nextLine();
System.out.println("\nEnter the replacing letter:");
String add = input.nextLine();
System.out.println(replaceLetter(word, replace, add));
}
public static String replaceLetter(String word, String letterToReplace, String add)
{
String newWord = "";
for(int i = 0; i < word.length(); i++)
{
if(word.substring(i, i+1).equals(letterToReplace))
{
String front = word.substring(0, word.indexOf(letterToReplace));
String back = word.substring(word.indexOf(letterToReplace)+1);
newWord = front + add + back;
}
}
return newWord;
}
}
There are 2 problems.
First, your program updates newWord everytime,
but whenever newWord is updated, it is calculated with not-updated word.
if(word.substring(i, i+1).equals(letterToReplace))
{
String front = !!!!!word!!!!!.substring(0, word.indexOf(letterToReplace));
String back = !!!!!word!!!!!.substring(word.indexOf(letterToReplace)+1);
newWord = front + add + back;
}
Second, why substring() in the if block does not use i?
String front = word.substring(0, !!!!!word.indexOf(letterToReplace)!!!!!);
String back = word.substring(!!!!!word.indexOf(letterToReplace)+1!!!!!);
The reason why your algorithm is not working, is that you're assigning a new String to newWord every time you replace a letter. So you will only get an output of the last replacement.
Every time the loop checks the the original string word.
First, your program updates newWord every-time, but whenever newWord is updated, it is calculated with not-updated word.
Just remove the variable newWord and perform operations on variable word only as presented in the following code:
import java.util.Scanner;
public class Letter
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println("\nEnter the letter you want to replace:");
String replace = input.nextLine();
System.out.println("\nEnter the replacing letter:");
String add = input.nextLine();
System.out.println(replaceLetter(word, replace, add));
}
public static String replaceLetter(String word, String letterToReplace, String add)
{
for(int i = 0; i < word.length(); i++)
{
if(word.substring(i, i+1).equals(letterToReplace))
{
String front = word.substring(0, word.indexOf(letterToReplace));
String back = word.substring(word.indexOf(letterToReplace)+1);
word = front + add + back;
}
}
return word;
}
}
You could simply use String#replace or String#replaceAll. Just take a look into the java-doc to understand how they work.
Because you are using word.indexOf(letterToReplace) which will always return the first index of string. So, Instead, you need to use word.indexOf(letterToReplace,i); with minor code, changes will help you to solve your problem. Try it yourself.
Happy Coding !!!
Trying to split out a string and output the penultimate word inputted by the user, but the .split() only seems to be outputting a single string into the array so its not working?
import java.util.*;
public class Random_Exercises_no60 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a sentence.");
String sentence = sc.next();
String[] words = sentence.split("\\s+");
System.out.println(words.length); // Just to check the array
System.out.println("Penultimate word " + words[words.length - 2]);
}
}
Problem is not with the split method, rather you should use nextLine instead of next:
String sentence = sc.nextLine();
The answer by #Aomine should resolve your problem. If you really wanted to use Scanner#next() directly, then you could also try setting the scanner's delimiter to be newline:
Scanner sc = new Scanner (System.in);
sc.useDelimiter(Pattern.compile("\\r?\\n"));
Then, calling Scanner#next() should default to returning the next full line.
You can use the whitespace regex
str = "Hello spilt me";
String[] splited = str.split("\\s+");
The split is working correctly. Reading of information from console is correct. Below changes should work.
public class Random_Exercises_no60 {
public static void main(String[] args) {
Scanner sc = new Scanner (System.in);
System.out.println("Please enter a sentence.");
String sentence = sc.nextLine();
String[] words = sentence.split("\\s+");
System.out.println(words.length); // Just to check the array
for (String currentWord : words ) {
System.out.println("The current word is" + currentWord);
}
}}
I have a question regarding StringBuilder. I'm trying to write a program that takes the user input : for example "DOG DOG CAT DOG DOGCAT", then asks the user to input a word they would like to change and what they would like to change it to. It should then replace all occurrences and print the result.
I have a code:
public class ChangeSentence
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
String text = sc.nextLine();
StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String rep = sc.nextLine();
System.out.println("For what do you want to change it: ");
String change = sc.nextLine();
System.out.println(Pattern.compile(x.toString()).matcher(rep).replaceAll(change));
}
}
How should I change it to achieve the result?
Thanks!
**Forgot to mention, I need to use the StringBuilder (without it i know how to write it).
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Write text: ");
original = sc.nextLine();
//StringBuilder x = new StringBuilder(text);
System.out.println("Write which word would you like to change: ");
String replacableWord = sc.nextLine();
System.out.println("For what do you want to change it: ");
String newWord = sc.nextLine();
String output = original.replace(replacableWord ,newWord);
System.out.println(output);
}
You just use the function replace on the original String and the
first parameter is the target String
the
second parameter is the replacement String
Last line should be replaced by following:
System.out.println(text.replaceAll(rep, change));
It's simple. You have to excercise a little
I want to be able to output the letter size of each word. So far my code only outputs the letter size of the first word. How do I get it to output the rest of the words?
import java.util.*;
public final class CountLetters {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String words = sc.next();
String[] letters = words.split(" ");
for (String str1 : letters) {
System.out.println(str1.length() );
}
}
}
It's just because next returns only the first word (or also called the first 'token'):
String words = sc.next();
To read the entire line, use nextLine:
String words = sc.nextLine();
What you are doing should work then.
The other thing you can do is go ahead and use next all the way (instead of a split) because Scanner already searches for tokens using whitespace by default:
while(sc.hasNext()) {
System.out.println(sc.next().length());
}
Using sc.next() will only let the scanner take in the first word.
String words = sc.nextLine();
Iterate over all of the scanner values:
public final class CountLetters {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
while(sc.hasNext()) {
String word = sc.next();
System.out.println(word.length() );
}
}
}
I'm trying to find the smallest word in a user entered string. This is what I have so far:
import java.util.*;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String myText = sc.next();
String[] myWords = myText.split(" ");
int shortestLength,shortestLocation;
shortestLength=(myWords[0]).length();
shortestLocation=0;
for (int i=1;i<myWords.length;i++) {
if ((myWords[i]).length() < shortestLength) {
shortestLength=(myWords[i]).length();
shortestLocation=i;
}
}
System.out.println(myWords[shortestLocation]);
}
If I entered "SMALLEST WORD SHOULD BE A", the output should be A but it just gives me the first word of the string. Any ideas?
Your algorithm is fine, but instead of using next():
String myText = sc.next();
Which will only read a single token, i.e., the first word, use nextLine(), which will read the entire line:
String myText = sc.nextLine();
To take the full string you have to use the method
sc.nextLine();
thus it will take the complete string.