Replace a string. - java

I've replaced a string so that all the letters appear as **'s however when I ask the user for input of a char, I can't seem to get the letters to revert back from *'s into strings. I will show you below what I have done in my code:
System.out.println(randomPirateWord.replaceAll("\\S", "*"));
System.out.println("guess a letter");
char letterGuesed = input.findInLine(".").charAt(0);
System.out.println(randomPirateWord.replaceAll("\\S"+letterGuesed,"*"));

Method replaceAll works in the opposite direction. First is a regular expression, and next the replacement for match, so you replace guessed letters with '*' and that's propably opposite to what you want to achieve.

I would use a String that holds your hiddenWord, and in a different function just display the length of the string in *s, then compare the letterGuessed to hiddenWord and change the *s back to the hiddenWord that way.

Maybe not with replace all, but this seems to work:
import java.util.Scanner;
class hola{
public static void main(String args[]){
Scanner sc = new Scanner(System.in);
String randomPirateWord = "HelloWorld";
System.out.println("");
boolean notComplete = true;
char words[] = new char[randomPirateWord.length()];
char words2[] = new char[randomPirateWord.length()];
for(int i = 0; i < randomPirateWord.length(); i++){
words[i] = randomPirateWord.charAt(i);
words2[i] = '*';
}
while(notComplete){
System.out.print("Type a letter: ");
char letter = sc.next().charAt(0);
notComplete = false;
for(int i = 0; i < randomPirateWord.length(); i++){
if(words[i] == letter){
words2[i] = letter;
}
}
for(int i = 0; i < randomPirateWord.length(); i++){
System.out.print(words2[i]);
}
for(int k = 0; k < randomPirateWord.length(); k++){
if(words2[k] == '*'){
notComplete = true;
break;
}
}
System.out.println("");
}
}
}

Related

How to reverse the word after getting a Capital letter at the end of the word in JAVA?

Suppose you have a String and a CAPITAL letter in that indicates ending of a word. For example, if you have wElovEcakE where E, E and K indicates end of the words wE, lovE and cakE respectively. You need to reverse each word (as you know where it ends). Don’t reverse the String as a whole. To illustrate, if we give wElovEcakE as input output should be EwEvolEkac. See wE became Ew, lovE became Evol and so on....
And the way i tried to approach with ..
import java.util.Scanner;
public class Alternative {
public static void main(String[]args) {
Scanner robo=new Scanner (System.in);
System.out.println("Enter a word ");
String word=robo.nextLine();
char[] array=word.toCharArray();
for(int i =0;i<array.length;i++){
int count =0;
for(int j=0;j<=("EMPTY");j++) // here i am trying to operate a loop where it will work up to the Capital letter.
count ++;
}
//Code incomplete
}
}
}
Above i have mentioned "EMPTY" in the condition part ... i want to operate a loop where my loop will work up to the capital letter , then i will count all the letter that i have counted up to capital letter then last step will be like i will make another loop where i will reverse all the letter where condition for the loop will <=count ;Example:lovE (counted 4 letters i will reverse four times back).
Can you guys help me to write the condition at "EMPTY" part if you think that my approach is correct ..
Can you guys help me to solve the problem in any other way ?
test if this works for you:
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
String textInvert = "";
int indexAnt = 0;
for (int i = 0; i < word.length(); i++) {
if (Character.isUpperCase(word.charAt(i))) {
String wordSplit = word.substring(indexAnt, i + 1);
for (int j = wordSplit.length() - 1; j >= 0; j--)
textInvert += wordSplit.charAt(j);
indexAnt = i + 1;
}
}
System.out.println(textInvert);
Here is my solution with Regex pattern
String[] in = "wElovEcakE".replaceAll("([A-z]+?[A-Z])","$1,").replaceAll(",$","").split(",");
String out = "";
for(String current: in){
StringBuilder temp = new StringBuilder();
temp.append(current);
out+=temp.reverse();
}
System.out.println(out);
Result:
EwEvolEkac
Here is a solution that makes use of the StringBuilder class to hold and reverse each found word.
Scanner robo = new Scanner (System.in);
System.out.println("Enter a word:");
String word = robo.nextLine();
robo.close();
String upperCase = word.toUpperCase(); //used to find uppercase letters
StringBuilder builder = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
char nextChar = word.charAt(i);
builder.append(nextChar);
if (nextChar == upperCase.charAt(i)) {
String subWord = builder.reverse().toString();
System.out.print(subWord); //It's not clear what to do with the found words
builder = new StringBuilder();
}
}
System.out.println();
Example
Enter a word:
makEmorEpiE
EkamEromEip
You can try this solution:
String textInvert = "wElovEcakE";
String revertText = textInvert
.chars().mapToObj(c -> (char) c)
.reduce(new LinkedList<>(Arrays.asList(new StringBuilder())), (a, v) -> {
a.getLast().append(v);
if (Character.isUpperCase(v)) {
a.add(new StringBuilder());
}
return a;
}, (a1, a2) -> a1)
.stream()
.map(s -> s.reverse())
.reduce(StringBuilder::append)
.map(StringBuilder::toString)
.get();
System.out.println(revertText);
public class Alternative {
public static void main(String[] args) {
Scanner robo = new Scanner(System.in);
System.out.println("Enter a word ");
String word = robo.nextLine();
char[] array = word.toCharArray();
int count = -1;
for (int i = 0; i < array.length; i++) {
if (Character.isUpperCase(array[i])) { //find the upper case letters in the word
for (int j = i; j > count; j--) //loop through the letters until the last count variable value is encountered
System.out.print(array[j]); //print the reversed values
count = i; //assign the last encountered uppercase letter's index value to count variable
}
}
}
}

How to create a function that takes a character and string and returns the index of this character in the string

i'm trying to solve the hangman game exercise .
the hangman game is randomly generates a word and
prompts the user to guess one letter at a time. Each
letter in the word is displayed as an asterisk. When the user makes a correct
guess, the actual letter is then displayed. When the user finishes a word, display
the number of misses and ask the user whether to continue to play with another
word.
everything was good till i have an bug this bug is when i run the program
if the word that pecked is such (overflow) the first 'O' in the word appear but the second 'O' doesn't 'cause the program can't Differentiates between both.
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
char again = 'y' ;
int missed = 0;
String[] words = {"computer" , "programming" , "web" , "android"};
do{
String word = words[(int)(Math.random()*4)];
int size = word.length();
char[] asterisk = new char[size];
for(int i=0; i<size; i++){
asterisk[i] = '*';
}
do{
System.out.print("(Guess) Enter a letter in word ");
for(int i=0; i<asterisk.length; i++) System.out.print(asterisk[i]);
char guess = input.next().charAt(0);
for(int i=0; i<asterisk.length; i++){
if(guess==(char)word.charAt(i)){
int Index_of_guess=where(guess,word);
asterisk[Index_of_guess]=guess;
}
else missed++;
}}while(check(asterisk));
System.out.print("The word is ");
for(int i=0; i<asterisk.length; i++) System.out.print(asterisk[i]);
System.out.println(" You missed " + missed + " time");
if(missed>1)
System.out.print("s");
System.out.println("Do you want to guess another word? Enter y or n > ");
again = input.next().charAt(0);
}while(again=='y');
}
public static boolean check(char[] asterisk){
for(int i=0; i<asterisk.length; i++){
if(asterisk[i]=='*')
return true;
}
return false;
}
public static int where(char guess, String word){
for(int i=0; i<word.length(); i++){
if(guess== word.charAt(i))
return i;
}
return 0;
}
Your where() method is completely unnecessary and the reason your program isn't working, since it's returning the index of the first occurrence of the character. Simply replace
if(guess == (char) word.charAt(i)) {
int Index_of_guess = where(guess,word);
asterisk[Index_of_guess] = guess;
}
with
if(guess == (char) word.charAt(i)) {
asterisk[i] = guess;
}

Check each position in the input entry and return the number of times a character occurs

I wrote the following code but I can't seem to convert the string to a char and then search the input entry string. My code is below. Any helpful tips would be greatly appreciated. I'm supposed to use a while loop but felt like for was easier to start with.
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String inputEntry;
String inputCharacter;
int length;
int i;
int counter = 0;
System.out.println("Enter a string: ");
inputEntry = in.next();
System.out.println("Enter a letter: ");
inputCharacter = in.next();
length = inputCharacter.length();
if (length == 1) {
for(i = 0; i <= inputEntry.length(); i++){
char c = inputCharacter.charAt(0);
if (inputEntry.charAt(i) == c){
counter++;
}
}
}
else {
System.out.println("The input letter was not a single letter.");
}
}
}
It looks like the only problem in your code is that you are using <= instead of < within your loop. <= is incorrect because it passes string length as an index, but first character resides at charAt(0), and last character resides at charAt(inputEntry.length() - 1)
Replacing your loop declaration with the following will do the trick:
for(i = 0; i < inputEntry.length(); i++){
Then you also need to System.out.println(counter); after the for loop.

Finding substring in a given string by changing into char array

i am working on the following program. but its not giving me the correct output for string "nameiskhan" and substring as"name".
i know this might be a duplicate question but i couldn't find the desired answer in those questions.
import java.util.*;
import java.lang.String;
public class CheckingSubstring2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter a String: ");
String string1 = input.next();
System.out.println("Please enter a second String: ");
String substring = input.next();
if (isSubstring(string1, substring)) {
System.out.println("The second string is a substring of the first.");
} else {
System.out.println("The second string is NOT a substring of the first.");
}
}
public static boolean isSubstring(String string1, String substring) {
char c[]=string1.toCharArray();
char d[]=substring.toCharArray();
boolean match = true;
for (int i = 0; i < c.length; i++) {
for (int j = 0; j < d.length; j++) {
if (c[i] == d[j]) {
match = true;
} else {
match = false;
}
}
}
return match;
}
}
As you want to do it without contains, how about this?
What I do here is that going through the original string one pass and check if the substring can be found as consecutive characters in the main String.
public static boolean isSubstring(String string1, String substring) {
char c[]=string1.toCharArray();
char d[]=substring.toCharArray();
for (int i = 0; i < c.length; i++) {
if(c[i] == d[0]){
boolean match = false;
for(int j = 0; j < d.length; j++){
if(c[i+j] != d[j]){
match = false;
break;
} else{
match = true;
}
}
if(match) return true;
}
}
return false;
}
I would suggest becoming familiar with different debugging techniques. A very quick and easy one is a print statement. For example, you can print the values that you are comparing to make sure it looks reasonable. It will also give you an indication of how many times your loop is running. Stepping through the algorithm, the first two characters to be compared are c[0] = 'n' and d[0] = 'n'. That's good. The next two are c[0] = 'n' and d[1] = 'a'. That's not. Also, I assume you intend for the program to stop running if it finds a substring, but it doesn't appear that it would do so. Likewise, you might consider not comparing every element of the substring if a comparison has already been false.

Count the occurrences of a letter in a string

I am trying to write a for loop in Java that will count the occurrences of a letter in a string. The user will enter the letter to count and the string in which to search. This is a very basic code, and we have not gotten to arrays or much else yet. (I realize that I declared letter twice, but my brain is dead at this point) This is what I have tried so far and am having trouble with, any help is appreciated:
Ok I changed my code per suggestions, but now it is only reading the first word of my sentence?
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char letter;
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int count = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch == letter) {
count++;
}
}
System.out.printf("There are %d occurrences of %s in %s", count,
letter, sentence);
}
}
I see a couple of issues. First you have two variables with the same name.
Second your if condition check for the lenght of the sentence to be greater then 0 instead of checking for character equality.
Scanner in = new Scanner(System.in);
char inLetter = "";
String sentence = "";
System.out.println("Enter a character for which to search");
inLetter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (inLetter == ch) {
letter++;
}
}
System.out.print(sentence.charAt(letter));
I would also strongly suggest to validate the input (which is not done in the example above) instead of just assuming you got 1 character from the first input and 1 sentence in the second.
Your if (sentence.length() <= 0) { is not right. Change your condition like:
System.out.println("Enter a character for which to search");
letter = in.next();
System.out.println("Enter the string to search");
sentence = in.next();
char searchLet=letter.charAt(0); // Convert String to char
int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (searchLet== ch) { // Check the occurrence of desired letter.
letter++;
}
}
System.out.print(sentence.charAt(letter));
if (sentence.length() <= 0) {
letter++;
}
The above part of code in your program is wrong. This will never be true until otherwise you input an empty string.
And basically this is not the correct logic. You will have to use the direct comparison.
No need to loop:
String sentence = "abcabcabcd";
String letter = "b";
int numOfOccurences = sentence.length() -
sentence.replaceAll(letter, "").length();
System.out.println("numOfOccurences = "+numOfOccurences);
OUTPUT:
numOfOccurences = 3
Try this
forget String letter = "" <-- Delete
forget letter = in.next() <-- Delete
// There's no nextChar() method, so this is a work aroung
char ch = in.findWithinHorizon(".", 0).charAt(0);
int letter = 0;
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == ch) {
letter++;
}
}
System.out.println(letter); // print number of times letter appears
// You don't want this
System.out.print(sentence.charAt(letter)); // Makes no sense
Try this:
Char letter = '';
String sentence = "";
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
System.out.println("Enter the string to search");
sentence = in.next();
int count= 0;
for (int i = 0; i < sentence.length(); i++) {
char ch = sentence.charAt(i);
if (ch==letter) {
count++;
}
}
System.out.print(letter+" occurance:"+count);
You need to know the char you wanna search. You can use char charToSearch = letter.toCharArray()[0];
Define a variable, such as count to count the occurrences of a letter in a given string.
Loop the string and compare each char, if the char is equal to the char to search, then count++;
Example--->
int count = 0;
char charToSearch = letter.toCharArray()[0];
for (int i = 0; i < sentence.length(); i++) {
if (sentence.charAt(i) == charToSearch) {
count++;
}
}
System.out.printf("Occurrences of a %s in %s is %d", letter, sentence, count);
Hope this will helpful to you.
import java.util.Scanner;
public class CountCharacters {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter the string to search");
String sentence = in.nextLine();
System.out.println("Enter a character for which to search");
String letter = in.next();
int noOfOccurance = 0;
for (int i = 0; i < sentence.length(); i++) {
char dh=letter.charAt(0);
char ch = sentence.charAt(i);
if (dh==ch) {
noOfOccurance++;
}
}
System.out.print(noOfOccurance);
}
}
Sample Input Output:
Enter the string to search
how are you
Enter a character for which to search
o
No of Occurances : 2
try the indexOf() method.
it should work
your Scanner class has not moved to the next line after reading the character
letter = in.next().charAt(0);
add another in.nextLine() before reading the input string
System.out.println("Enter a character for which to search");
letter = in.next().charAt(0);
in.nextLine();
System.out.println("Enter the string to search");
sentence = in.nextLine();
old thread but hope this helps :)

Categories