Replace a certain character from a String - java

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 !!!

Related

How can I replace the letters in a String?

I am supposed to write code that replaces a letter in an input. For example, if the word is "hello" and the letter to replace is "l" and put "y" it would make "heyyo". I just don't know what to do after the user inputs.
import java.util.Scanner;
public class Letter
{
public static void main(String[] args)
{
// Ask the user for 3 things: their word, letter they want to replace,
// and replacing letter.
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println();
System.out.println("Enter the letter you want to replace:");
String letter = input.nextLine();
System.out.println();
System.out.println("Enter the replacing letter:");
String replace = input.nextLine();
System.out.println();
// Call the method replaceLetter and pass all 3 of these items to it for
// string processing.
}
// Modify this method so that it will take a third parameter from a user that is the String
//they
//want
//to replace letterToReplace with. This method should return the modified String.
public static int replaceLetter(String word, String letterToReplace, String replacement)
{
int count = 0;
for(int i = 0; i < word.length(); i++)
{
if(word.substring(i, i+1).equals(letterToReplace))
{
count++;
}
}
return count;
}
}
Try doing the next, replacing the char at the position if it is the same as the letter to replace.
for(int i = 0; i < word.length(); i++)
{
if(word.charAt(i) == letterToReplace)
{
word = word.substring(0, i)
+ replacement
+ word.substring(i + 1);
count++;
}
}
Or you could just do the next:
word = word.replace(letterToReplace, replacement);
YCF_L is correct, the best way would be with replace. If you need to do things programatically for some reason, this will work:
public static void main(String[] args)
{
// Ask the user for 3 things: their word, letter they want to replace,
// and replacing letter.
Scanner input = new Scanner(System.in);
System.out.println("Enter your word:");
String word = input.nextLine();
System.out.println();
System.out.println("Enter the letter you want to replace:");
String letter = input.nextLine();
System.out.println();
System.out.println("Enter the replacing letter:");
String replace = input.nextLine();
System.out.println();
// Call the method replaceLetter and pass all 3 of these items to it for
// string processing.
System.out.println(replaceLetter(word, letter, replace));
}
// Modify this method so that it will take a third parameter from a user that is the String
//they
//want
//to replace letterToReplace with. This method should return the modified String.
public static String replaceLetter(String word, String letterToReplace, String replacement)
{
//Short way:
String wayOne = word.replace(letterToReplace, replacement);
//Long way:
String wayTwo = "";
for(int i = 0; i < word.length(); i++){
if(word.charAt(i) == letterToReplace.charAt(0)){
wayTwo += replacement;
} else {
wayTwo += Character.toString(word.charAt(i));
}
}
return wayOne + " VS " + wayTwo;
}

Removing a word in a string (RemoveString)

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.

Write a program that prompts the user to input a sequence of characters and outputs the numbers of vowels

import java.util.*;
public class VowelCounter
{
public static void main(String[] args)
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Input a series of characters: ");
String letters = keyboard.next();
int count = 0;
for (int i = 0; i < letters.length(); i++)
{
char characters = letters.charAt(i);
if (isVowel(characters) == true)
{
count++;
}
}
System.out.println("The number of vowels is: " + count);
}
public static boolean isVowel(char characters)
{
boolean result;
if(characters=='a' || characters=='e' || characters=='i' || characters=='o' || characters=='u')
result = true;
else
result = false;
return result;
}
}
The code works but im suppose to input "Spring break only comes once a year." which if i do with the spaces my program will only find the vowels of Spring. how do i make it so it will skip the spaces and read the whole sentence.
This is your problem:
String letters = keyboard.next();
It has nothing to do with the vowel-counting part - but everything to do with reading the value. The Scanner.next() method will only read to the end of the token - which means it stops on whitespace, by default.
Change that to
String letters = keyboard.nextLine();
and you should be fine.
You should verify this is the problem by printing out the string you're working with, e.g.
System.out.println("Counting vowels in: " + letters);
When you do:
String letters = keyboard.next();
The Scanner stops reading at the first whitespace.
To read the complete phrase until you press enter, you should use nextLine() instead:
String letters = keyboard.nextLine();
Just use
String letters = keyboard.nextLine();
instead of
String letters = keyboard.next();
This is because .nextLine() will read line by line so that you can have your complete statement in latters. Hope this will help you

JAVA basic iterator

this was the solution to my homework and the purpose was to reverse each word in a string based on user inputting a sentence. I have completed this on my own, but I'm just wondering how the iterator worked in this piece of code. I don't understand the delcaration of tempword = ""; and how he printed out each word delimited by spaces.
import java.util.Scanner;
public class StringReverser
{
public static void main(String args[])
{
String sentence;
String word;
String tempWord = "";
Scanner scan = new Scanner(System.in);
Scanner wordScan;
System.out.print("Enter a sentence: ");
sentence = scan.nextLine();
wordScan = new Scanner(sentence);
while(wordScan.hasNext())
{
word = wordScan.next();
for(int numLetters = word.length() - 1; numLetters >= 0; numLetters--)
tempWord += word.charAt(numLetters);
System.out.print(tempWord + " ");
tempWord = "";
}
System.out.println();
}
}
this bit adds in the spaces
System.out.print(tempWord + " ");
this bit reverses it
for(int numLetters = word.length() - 1; numLetters >= 0; numLetters--)
tempWord += word.charAt(numLetters);
this bit sets it up for the next word
tempWord = "";
The for loop counts backwards, from the index of the last character in the word to the first (in zero based notation)
The print prints the reversed word + a space (" "), the fact it uses print in place of println is because println would add a carriage return putting each word in a different line.
The tempWord = ""; at the end of each iteration reset the variable so it can be reused.

Find the smallest word in a string in Java

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.

Categories

Resources