How can I replace / edit only a specific word in Java? - java

I want a specific word being replaced/ edited. But unfortunately, other words are replaced too who contain the word to be replaced.
Example:
String test = "I am a ool tool";
Now if I want to replace the word "ool" with something, "tool" is gonna be changed as well. So how can I solve this problem? I JUST want ool to be edited. "tool" should stay like it is.
Here some code:
public class StringMethoden {
public static void main(String[] args) {
String bsp = "I am a ool tool";
if (bsp.matches("(.*)ool(.*)")){
bsp = bsp.replaceAll("ool", "test");
System.out.println(bsp);
}
else {
System.out.println("sentence does not conain 'ool' !");
}}
Outut: I am a test ttest

Word boundaries (\b) in Java RegEx make sure a certain point in the string is the start/end of a word.
bsp = bsp.replaceAll("\\bool\\b", "test");

Here is a similar approach for the issue, we can also use .contains() method in the following manner, feel free to ask questions if any.
String bsp = "I am a ool tool";
if (bsp.contains(" ool")) {
bsp = bsp.replaceAll(" ool", " test");
System.out.println(bsp);
} else {
System.out.println("sentence does not conain 'ool' !");
}
Output:
I am a test tool

Related

How do I use the contains method with "if, else" statement?

I am having difficulty triggering my "if" statement. When I input "I like my 'anything'", which the CharSequence should be searching for, the code kicks out the error from the else statement. I've tried to see if the contains method wasn't reading whitespace by attempting to identify just one letter using the CharSequence. That didn't help. I also attempted to change my contains method into a boolean and run the if statement if the boolean were true. That also did not work. I've searched around a bit at other code and it seems to look similar. Eclipse isn't flagging any errors I'm just beginning and have little clue on what else to attempt. If there are any additional hints on how to clean my code up or methods that might work better. Please give some constructive criticism.
import java.util.Scanner;
public class hello {
public static void main(String args[]) {
Scanner scan = new Scanner(System.in);
try {
System.out.println("Hi, what is your name?");
String name1 = scan.next();
System.out.println("Hello "+ name1 + ". Tell me what you like about yourself?\n"
+ "Please pretext what you like about yourself with the phrase 'I like my'.");
String selfEsteem = scan.next();
CharSequence searchString = "I Like my";
if (selfEsteem.contains(searchString)) {
selfEsteem = selfEsteem.replace("my", "your");
System.out.println(selfEsteem + "also.");
} else {
System.err.println("Error: User did not use 'I like my' input format");
}
} finally {
scan.close();
}
}
}
output:
Hi, what is your name?
Janet
Hello Janet. Tell me what you like about yourself?
Please pretext what you like about yourself with the phrase 'I like my'.
I like my boobs
Error: User did not use 'I like my' input format
Your searchString is "I Like my", while your text has "I like my". So I assume your user will enter the lowercase one and contains is case sensitive so it won't find it.
Change to:
CharSequence searchString = "I like my";
You are searching for "I Like my" while your error massages says it should be 'I like my'.
It's case sensitive.
Either type in "I Like my" or change your searchString to "I like my".
Use
if (selfEsteem.containsIgnoreCase(searchString))
...
instead of
if (selfEsteem.contains(searchString))
...
Then it doesn't matter what case the user types in.

transform short word to original word

I used some word counting algorithm and by a closer look I was wondering because I got out less words than originally in the text because they count for example "it's" as one word. So I tried to find a solution but without any success, so I asked myself if their exist anything to transform a "short word" like "it's" to their "base words", say "it is".
Well, basically you need to provide a data structure that maps abbreviated terms to their corresponding long versions. However, this will not be as simple as it sounds, for example you won't want to transform "The client's car." to "The client is car."
To manage these cases, you will probably need a heuristic that has a deeper understanding of the language you are processing and the grammar rules it incorporates.
I just built this from scratch for the challenge. It seems to be working on my end. Let me know how it works for you.
public static void main(String[] args) {
String s = "it's such a lovely day! it's really amazing!";
System.out.println(convertText(s));
//output: it is such a lovely day! it is really amazing!
}
public static String convertText(String text) {
String noContraction = null;
String replaced = null;
String[] words = text.split(' ');
for (String word : words) {
if (word.contains("'s")) {
String replaceAposterphe = word.replace("'", "$");
String[] splitWord = replaceAposterphe.split('$');
noContraction = splitWord[0] + " is";
replaced = text.replace(word, noContraction);
}
}
return replaced;
}
I did this in C# and tried to convert it into Java. If you see any syntax errors, please point them out.

How come my split("\n") isn't working

I've tried "\n\n" and "\r" and everything else, including replaceAll("\r\n", "n") and I still do not understand why it doesn't work. I've also tried "\w", "\n", "\n+" - I've basically tried everything under "My split("\n") doesn't work" on Google search.
I'm trying to split a word with a lot of "\n". I basically have two different classes. One generates this word, and via the other class constructor object transfers it into the split("\n") method. But whatever I do, the array still stays empty.
I've also tried word.split(System.getProperty("line.separator")) even though I didn't have a clue as to what it meant, but it also came up under one of the solutions to this problem.
Here's my Code:
//in Class A
public String getWord()
{
word = word +"\n" + horizontal;
return word;
}
//in Class B
classA a = new classA();
String grid = a.getWord();
String [] lines = grid.split("\n");
EDIT: Sorry, typo mistake, I'll just ask again later. I did actually put grid.split("\n") in my code. What now? The array really is empty. I did System.out.println(array.length) and it was 0. Also, I typed System.out.println("array is " + array) and it only gave me "array is" as output. I know I'm making a stupid mistake somewhere, and I know I can't expect people to answer my question if I don't know what info to provide.
I also wanted to add some stuff in the comments section here for the comfort of those sitting in front of their laptops...
word and horizontal is a string. It's actually a crossword puzzle together.
See? Look!
LONDONPYVRAOMNDDEFSG
GCPZVBATHYXAZXEZIMOZ
NKDGBERLINCHPLTMHMSM
ZMUKPGCHRKDTYGIMRLHO
TVRWBXPRETORIAJBVKWT
OGIVSDFULULHQHAHEJNV
PNWEJHBAKBJZNBPARIS
PHKCZCYGTXEEXDUCPMXF
QIMQMABRASILIALJOFJQ
GXNXKTAHIQMMIFPSYDLI
CAIROYKZYSWEFPUZPKRG
BTNAUNIDQAYVYAPGWWIN
QXZMQSZBTCBEIJINGBSD
QWQRYTBPTKRBCJUOMJTV
SODHAMSTERDAMEMSLVAM
YQHEVNXQQJXCDZKEYQVT
NAIROBISVDNTCFJNYDEG
AKXVOIGYTZTJHGIAFIKZ
BAGHDADSADJTWOOMVRYT
YCPOBXQQMQKBTDMYPYWT
It's city names. At the end of this, I'm supposed to show the solution to the puzzle by changing cases. I know how to do this, but the problem is that I can't seperate them into lines anymore. I don't know why. That's my only problem here. It seems to work for everyone, except for me.
Answers with clues will be appreciated? To delve into a dark and deep mystery...
It should be
grid.split("\n");
not
instance.split("\n")
Call grid.split("\n");
You can't split a class.
Better a.getWord().split("\n");
In your code there isn't no method named split , also your didn"t call your method getword inside System.out.println() ....
First Class :
public class A {
public String returnedWord ="";
public String getWord(String word , String horizontal)
{
returnedWord = word +"\n" + horizontal;
return returnedWord ;
}
}
the Second Class :
public class B {
public String word = "Hello";
public String horizontal = "World";
public static void main (String [] args ) {
A a = new A();
System.out.println(a.getword(word,horizontal));
}
}
you will get the output below :
Hello
World

Replacing words in a String java

Say I have a string,
String templatePhrase = "I have a string that needs changing";
I also have a method to replace words in any given String. Here is the method:
public String replace(String templatePhrase, String token, String wordToPut) {
return templatePhrase.replace(token, wordToPut);
}
Now say (for the sake of my actual task) I have all the words in my String str in a List named wordsInHashtags. I want to loop through all the words in wordsInHashtags and replace them with words from another List named replacement using the replace() method. Each time the loop iterates, the modified String should be saved so it will hold its replacement(s) for the next loop.
I will post my code if anyone would like to see it, but I think it would confuse more than help, and all I am interested in is a way to save the modified String for use in the next iteration of the loop.
I was just reading about strings in beginning Java 2 the other day, :"Strings Objects are immutable" Cant be changes basically however StringBuffer Objects were created to deal with such a circumstance as i understand it. You could try:
StringBuffer templatePhrase = "I have a string to be changed";
templatePhrase.replace(token, wordToPut);
String replacedString = (String)templatePhrase;
Line 3 may cause a problem?
public class Rephrase {
public static void main(String[] args) {
/***
Here is some code that might help to change word in string. originally this is a Question from Absolute Java 5th edition. It will change two variable whatever you want but algorithm never change.So the input from keyboard or any other input source.
********/
String sentence = "I hate you";
String replaceWord = " hate";
String replacementWord = "love";
int hateIndex = sentence.indexOf(replaceWord);
String fixed = sentence.substring(0,hateIndex)+" "+replacementWord+sentence.substring(hateIndex+replaceWord.length());
System.out.println(fixed);
}
}

Efficent way to replace underscore with char or string

I have researched this topic for a while, but without much success. I did find the StringBuilder and it works wonders, but that's as far as I got. Here is how I got my hangman program to work like it should:
if(strGuess.equalsIgnoreCase("t")){
mainword.replace(0,1,"T");
gletters.append('T');
}
else if(strGuess.equalsIgnoreCase("e")){
mainword.replace(1,2,"E");
gletters.append('E');
}
else if(strGuess.equalsIgnoreCase("c")){
mainword.replace(2,3,"C");
gletters.append('C');
}
else if(strGuess.equalsIgnoreCase("h")){
mainword.replace(3,4,"H");
gletters.append('H');
}
else if(strGuess.equalsIgnoreCase("n")){
mainword.replace(4,5,"N");
gletters.append('N');
}
else if(strGuess.equalsIgnoreCase("o")){
mainword.replace(5,6,"O");
mainword.replace(7,8,"O");
gletters.append('O');
}
else if(strGuess.equalsIgnoreCase("l")){
mainword.replace(6,7,"L");
gletters.append('L');
}
else if(strGuess.equalsIgnoreCase("g")){
mainword.replace(8,9,"G");
gletters.append('G');
}
else if(strGuess.equalsIgnoreCase("y")){
mainword.replace(9,10,"Y");
gletters.append('Y');
}
else{
JOptionPane.showMessageDialog(null, "Sorry, that wasn't in the word!");
errors++;
gletters.append(strGuess.toUpperCase());
}
SetMain = mainword.toString();
GuessedLetters = gletters.toString();
WordLabel.setText(SetMain);
GuessedLabel.setText(GuessedLetters);
GuessText.setText(null);
GuessText.requestFocusInWindow();
However, I can't do this for EVERY letter for EVERY word, so is there a simple and efficient way to do this? What I want is to have a loop of some sort so that I would only have to use it once for whatever word. So the word could be technology (like it is above) or apple or pickles or christmas or hello or whatever.
I have tried using a for loop, and I feel the answer lies in that. And if someone could explain the charAt() method and how/where to use it, that'd be good. The closest I got to being more efficient is:
for(i = 0; i < GuessWord.length(); i++) {
if (GuessWord.charAt(i) == guess2) {
mainword.replace(i,i,strGuess.toUpperCase());
}
So if you could use that as a basis and go off of it, like fix it? Or tell me something I haven't thought of.
It's a good question. There's clearly repeated code, so how do you replace all that with something reusable. Actually, you can dispense with all of your code.
That whole code block can be replaced by just one line (that works for every word)!
String word = "TECHNOLOGY"; // This is the word the user must guess
mainword = word.replaceAll("[^" + gletters + "]", "_");
This uses replaceAll() with a regex that means "any letter not already guessed" and replaces it with a underscore character "_". Note that Strings are immutable, and the replaceAll() method returns the modified String - it doesn't modify the String called on.
Here's some test code to show it in action:
public static void main(String[] args) {
String word = "TECHNOLOGY"; // what the user must guess
StringBuilder gletters = new StringBuilder("GOTCHA"); // letters guessed
String mainword = word.replaceAll("[^" + gletters + "]", "_");
System.out.println(mainword);
}
Output:
T_CH_O_OG_

Categories

Resources