I have one String generated of random characters that will encrypt another String given by the user by adding the first character from the String with the first character of the given String. It's working fine, but if the user were to enter multiple words with spaces in between, I want to choose the next character of the first String rather than code the space itself. Is that possible? This is what I have:
(random is the coded string and sentenceUpper is string given by user)
public static void encrypt(String sentenceUpper){
String newSentence = "";
for(int i = 0; i < sentenceUpper.length(); i++){
char one = random.charAt(i);
char two = sentenceUpper.charAt(i);
if(one < 'A' || one > 'Z'){
two = sentenceUpper.charAt(1 + i);}
char result = (char)((one + two)%26 + 'A');
newSentence += "" + result;
}
EDIT FOR BETTER EXPLANATION:
I have:
String random = "WFAZYZAZOHS";
I would like to code user input:
String upperCase: "YOU GO";
So, I'm going to take Y + L = U, etc...
to get :
"UTUSEN
"
But I see that there's a space in "YOU GO" , So I'd like to change it to:
WFA ZY + YOU GO = UTU SE.
I hope that's better explained.
The simplest way to do this would probably be to use an if statement to run the code in the loop only if the character is not a space. If you don't want to skip the character in the random string, you would need a separate variable to track the current character index in that string.
Example: Put this after defining one and two and put the rest of the loop inside it:
if(two==' '){
...
}
Then, add the space in the output:
else{
newSentence+=" ";
}
Related
Can someone help me here? I dont understand where's the problem...
I need check if a String have more than 1 char like 'a', if so i need replace all 'a' for a empty space, but i still want only one 'a'.
String text = "aaaasomethingsomethingaaaa";
for (char c: text.toCharArray()) {
if (c == 'a') {
count_A++;//8
if (count_A > 1) {//yes
//app crash at this point
do {
text.replace("a", "");
} while (count_A != 1);
}
}
}
the application stops working when it enters the while loop. Any suggestion? Thank you very much!
If you want to replace every a in the string except for the last one then you may try the following regex option:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", " ");
somethingsomething a
Demo
Edit:
If you really want to remove every a except for the last one, then use this:
String text = "aaaasomethingsomethingaaaa";
text = text.replaceAll("a(?=.*a)", "");
You can also do it like
String str = new String ("asomethingsomethingaaaa");
int firstIndex = str.indexOf("a");
firstIndex++;
String firstPart = str.substring(0, firstIndex);
String secondPart = str.substring(firstIndex);
System.out.println(firstPart + secondPart.replace("a", ""));
Maybe I'm wrong here but I have a feeling your talking about runs of any single character within a string. If this is the case then you can just use a little method like this:
public String removeCharacterRuns(String inputString) {
return inputString.replaceAll("([a-zA-Z])\\1{2,}", "$1");
}
To use this method:
String text = "aaaasomethingsomethingaaaa";
System.out.println(removeCharacterRuns(text));
The console output is:
asomethingsomethinga
Or perhaps even:
String text = "FFFFFFFourrrrrrrrrrrty TTTTTwwwwwwooo --> is the answer to: "
+ "The Meeeeeaniiiing of liiiiife, The UUUniveeeerse and "
+ "Evvvvverything.";
System.out.println(removeCharacterRuns(text));
The console output is........
Fourty Two --> is the answer to: The Meaning of life, The Universe and Everything.
The Regular Expression used within the provided removeCharacterRuns() method was actually borrowed from the answers provided within this SO Post.
Regular Expression Explanation:
I am working on a codingbat problem:Given a string, return a version where all the "yak" are removed, but the "a" can be any char. The "yak" strings will not overlap. I am look at the solution but there is one part of that code I do not understand.....
How come the first part of the if statement "i = i+ 2" could return the string and you don't need anything else? I mean after all these three conditions are met and just write i = i + 2,and that's it. that is going to give you a String as a result. I don't get it, please help.
public String stringYak(String str) {
String result = "";
for (int i=0; i<str.length(); i++) {
// Look for i starting a "yak" -- advance i in that case
if (i+2<str.length() && str.charAt(i)=='y' && str.charAt(i+2)=='k') {
i = i + 2;
} else { // Otherwise do the normal append
result = result + str.charAt(i);
}
}
return result;
}
The code is selecting what characters to put in the new string.
We go through the characters one by one.
If we run into a "y.k", skip this whole section
Else add the character to the new string.
[a][b][y][c][k][d] => New String: [a] (a is okay)
.|..........................
[a][b][y][c][k][d] => New String: [a][b] (b is okay)
......|.....................
[a][b][y][c][k][d] => New String: [a][b] (Oops! We have run into the y.k
pattern, skip it) ..........|.................
[a][b][y][c][k][d] => New String: [a][b][d] (d is okay)
.....................|......
Final String: [a][b][d]
This may not be the style of answer you want, but a simple call to String#replaceAll() should work:
String str = "Some string yak containing yok.";
str = str.replaceAll("y.k", "");
Doing i = i + 2 is not going to give you any String it is simply incrementing the for loop so you do not need to re-evaluate the next two chars as they have already been evaluated.
The key point is in the else part, which will append the char if it is not y and the character after-next is also not k
I'm relatively new to coding and my teacher asked us to make a code for a hangman game. He told us that we must accomplish this without the use of Arrays. My question is along the lines of this: If I have a String that is declared by the user and then a correct letter is guessed, how would I specifically be able to replace a substituted underscore with the guessed letter?
For example...
input is "cats"
system types "_ _ _ _"
say I typed the letter "a" and I want the output to be:
"_ a _ _"
How would I get the placement number of that letter and then manipulate the underscore to make it the letter?
StringBuilder.charAt()
StringBuilder.setCharAt()
You may want to have a look at these methods.
For the purpose of printing, you may want StringBuilder.toString().
You could use substrings. Something like this.
String original = "apple";
String guessed = original;
String withUnderscores = "_____";
String guess = "a";
while (guessed.contains(guess))
{
int index = guessed.indexOf(guess);
withUnderscores = withUnderscores.substring(0, index) + guess + withUnderscores.substring(index + 1);
guessed = guessed.substring(0, index) + "." + guessed.substring(index + 1);
}
System.out.println(original);
System.out.println(guessed);
Use one variable to store the underscore string. (ie "____"
Use another variable to store the answer string. (ie "cats").
Get the users input and and loop through the string taking the character at each index. If any variable matches the input letter (string1.equals(string2)) replace the character in the underscore string at whatever index your loop is at.
Use charAt() to get the character at a place in a string.
You can do this with a String or the StringBuilder class. If you haven't learned about StringBuilder in your classes, you probably shouldn't use it for your assignment.
Try something like this (I would prefer to have the guesses on a Set, it would be more clear than using a string to hold them):
public String maskUnguessedLetters(String answer, String guessed) {
Char MASKED = '_';
StringBuilder sb = new StringBuilder();
for (Char c : answer.toCharArray()) {
sb.append(guessed.contains(c.toString())
? c
: MASKED);
}
return sb.toString();
}
I don't completely understand the question, but I think this might help.
final String trueWord="cats";
String guessWord="____";
String input="a";
//if the input matches
if(trueWord.contains(input)){
//last Index of input in trueWord
int lastEntry=-1;
//hold all indices of input character in trueWord
ArrayList<Integer> indices=new ArrayList<>();
while(trueWord.indexOf(input,lastEntry+1) >= 0){
lastEntry=trueWord.indexOf(input);
indices.add(lastEntry);
}
//now replace the characters at the indices
StringBuilder newGuessWord = new StringBuilder(guessWord);
for(int index:indices){
//replace one character at a time.
newGuessWord.setCharAt(index, input.charAt(0));
}
//the new word
guessWord=newGuessWord.toString();
}
This is the not the most optimised code but will definitely give you an idea of how your task can be done.
public static void main(String[] args) {
final String word = "cats";
Scanner scanner = new Scanner(System.in);
System.out.println("Guess the character");
String finalString = "";
char letter = scanner.next().charAt(0);
for (char s : word.toCharArray()) {
if (s == letter) {
finalString += s;
} else
finalString += "_";
}
System.out.println(finalString);
scanner.close();
}
I'm having problems with strings and I need a solution I'm trying to replace characters found at a certain position with a character found in also the same position for example
private String wordNormalize(String enteredWord,String dictionary){
String normalizedWord = null;
// remove empty spaces at beginning and at the end of the word and change to lower case
normalizedWord = enteredWord.trim().toLowerCase();
//normalize term, removing all punctuation marks
normalizedWord = normalizedWord.replaceAll("["+punctuationMarks2+"]", "[b,v]");
//normalize word removing to character if dictionary has english lang
normalizedWord = normalizedWord.replaceFirst("to ", " ");
//normalizeWord if dictionary has german
if(normalizedWord.length() > 0){
normalizedWord.replace("a,b,c","t,u,v");
/*for(int i = 0;i<normalizedWord.length();i++){
char currentChar = normalizedWord.charAt(i); // currently typed character
String s1= Character.toString(currentChar);
for(int j = 0;j<specialCharacters.length;j++){
s1.replaceAll("[ "+specialCharacters[i]+" ]",""+replaceCharactersDe[i]+"");
}
= str.replace("a,b,c","t,u,v");
}*/
}
//normalize term removing special characters and replacing them
/*for(int i = 0; i > specialCharacters.length;i++){
if(normalizedWord.equals(specialCharacters[i])){
normalizedWord = replaceCharactersDe[i];
}
}*/
return normalizedWord;
}
So if a user enters a its replaced with t and if a user enters b its replaced with u and if the user enters c it will be replaced with v and only in that order is this possible and if it is show me the right way its supposed to be done
It is not clear to me what you are trying to approach with
normalizedWord = normalizedWord.replaceAll("["+punctuationMarks2+"]", "[b,v]");
It does not seem right, but i don't know how to fix it because I don't know what it's trying to do. I guess what you are looking for is
normalizedWord = normalizedWord.replaceAll("\\p{Punct}", "");
On the other part you are doing nothing, because Strings are immutable. You want to do something like
normalizedWord = normalizedWord.replace("a,b,c","t,u,v");
but that would replace all occurrences of the substring "a,b,c" with the string "t,u,v"-
What you want is:
normalizedWord = normalizedWord.replace('a', 't');
normalizedWord = normalizedWord.replace('b', 'u');
normalizedWord = normalizedWord.replace('c', 'v');
We could work on a more general solution, but you have to show us how the dictionary , which is a String, is formatted.
How can I get the int value from a string such as 423e - i.e. a string that contains a number but also maybe a letter?
Integer.parseInt() fails since the string must be entirely a number.
Replace all non-digit with blank: the remaining string contains only digits.
Integer.parseInt(s.replaceAll("[\\D]", ""))
This will also remove non-digits inbetween digits, so "x1x1x" becomes 11.
If you need to confirm that the string consists of a sequence of digits (at least one) possibly followed a letter, then use this:
s.matches("[\\d]+[A-Za-z]?")
The NumberFormat class will only parse the string until it reaches a non-parseable character:
((Number)NumberFormat.getInstance().parse("123e")).intValue()
will hence return 123.
Unless you're talking about base 16 numbers (for which there's a method to parse as Hex), you need to explicitly separate out the part that you are interested in, and then convert it. After all, what would be the semantics of something like 23e44e11d in base 10?
Regular expressions could do the trick if you know for sure that you only have one number. Java has a built in regular expression parser.
If, on the other hands, your goal is to concatenate all the digits and dump the alphas, then that is fairly straightforward to do by iterating character by character to build a string with StringBuilder, and then parsing that one.
You can also use Scanner :
Scanner s = new Scanner(MyString);
s.nextInt();
Just go through the string, building up an int as usual, but ignore non-number characters:
int res = 0;
for (int i=0; i < str.length(); i++) {
char c = s.charAt(i);
if (c < '0' || c > '9') continue;
res = res * 10 + (c - '0');
}
Perhaps get the size of the string and loop through each character and call isDigit() on each character. If it is a digit, then add it to a string that only collects the numbers before calling Integer.parseInt().
Something like:
String something = "423e";
int length = something.length();
String result = "";
for (int i = 0; i < length; i++) {
Character character = something.charAt(i);
if (Character.isDigit(character)) {
result += character;
}
}
System.out.println("result is: " + result);