So, right now in my computer science class(a beginners class), we are focusing o
ID: 3820638 • Letter: S
Question
So, right now in my computer science class(a beginners class), we are focusing on an assignment called Letter Replacement. Basically, the purpose of the assignment is to enable us to build a better understanding on how to use a string builder class. However, the assignment requires that we have our program read in a word and then replace every other letter with an asterisk(Ex:*). My question is how can you replace letters in a string, specifically with an asterisk? I would appreciate a good explanation as I am very much a beginner and struggle with Computer Science. Thank you!
The computer language is in C++
An example of Input and Output is:
Enter a word: Sing
Output:
Alternate word: S*n*g
Explanation / Answer
import java.util.*;
public class HelloWorld{
public static void main(String []args){
Scanner input=new Scanner(System.in);
String word; /* variable to store input from user */
char ch='*'; /* character by which string needs to be replaced */
System.out.println("Enter a word: " ); /* Asking the user to enter a word */
word=input.next(); /* storing user entered word into word variable */
/* traversing the whole word */
for(int i=0;i<word.length();i++){
if(i%2!=0) /* if index is odd replace the character present here by '*' */
word=word.replace(word.charAt(i), ch);
}
/* printing the output */
System.out.println("Alternate word: "+word);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.