Java- I want to change a particular string with another one - java

import java.util.*;
import java.io.*;
public class OptimusPrime{
public static void main(String[] args){
System.out.println("Please enter the sentence");
Scanner scan= new Scanner(System.in);
String bucky=scan.nextLine();
int pOs=bucky.indexOf("is");
System.out.println(pOs);
if(pOs==-1){
System.out.println("the statement is invalid for the question");
}
else{
String nay=bucky.replace("is", "was");
System.out.println(nay);
}
}
}
Now I know the "replace" method is wrong as i want to change the particular string "is" and not the portion of other string elements. I also tried using SetChar method but I guess the "string is immutable" concept applies here.
How to go about it?

Using String.replaceAll() instead enables you to use a regex. You can use the predefined character class \W in order to catch a non-word character :
System.out.println("This is not difficult".replaceAll("\\Wis", ""));
Output :
This not difficult
The verb is disappeared but not the isfrom This.
Note 1 : It also removes the non-word character. If you want to keep it, you can capture it with some parenthesis in the regex then reintroduce it with $1:
System.out.println("This [is not difficult".replaceAll("(\\W)is", "$1"));
Output :
This [ not difficult
Note 2 : If you want to handle a string which begins with is, this line will not be enough but it is quite easy to handle with another regex.
System.out.println("is not difficult".replaceAll("^is", ""));
Output :
not difficult

If you use replaceAll instead, then you can use \b to use the word boundary to perform a "whole words only" search.
See this example:
public static void main(final String... args) {
System.out.println(replace("this is great", "is", "was"));
System.out.println(replace("crysis", "is", "was"));
System.out.println(replace("island", "is", "was"));
System.out.println(replace("is it great?", "is", "was"));
}
private static String replace(final String source, final String replace, final String with) {
return source.replaceAll("\\b" + replace + "\\b", with);
}
The output is:
this was great
crysis
island
was it great?

Simpler way:
String nay = bucky.replaceAll(" is ", " was ");
Match word boundary:
String nay = bucky.replaceAll("\\bis\\b", "was");

to replace string with another string you can use this
if Your string variable contains like this
bucky ="Android is my friend";
Then you can do like this
bucky =bucky.replace("is","are");
and your bucky's data will be like this Android are my friend
Hope this helps you.

Related

How to write a regex to split a String in this format?

I want to use [,.!?;~] to split a string, but I want to remain the [,.!?;~] to its place for example:
This is the example, but it is not enough
To
[This is the example,, but it is not enough] // length=2
[0]=This is the example,
[1]=but it is not enough
As you can see the comma is still in its place. I did this with this regex (?<=([,.!?;~])+). But I want if some special word (e.g: but) comes after the [,.!?;~], then do not split that part of string. For example:
I want this sentence to be split into this form, but how to do. So if
anyone can help, that will be great
To
[0]=I want this sentence to be split into this form, but how to do.
[1]=So if anyone can help,
[2]=that will be great
As you can see this part (form, but) is not split int the first sentence.
I've used:
Positive Lookbehind (?<=a)b to keep the delimiter.
Negative Lookahead a(?!b) to rule out stop words.
Notice how I've appended RegEx (?!\\s*(but|and|if)) after your provided RegEx. You can put all those stop words that you've to rule out (eg, but, and, if) inside the bracket separated by pipe symbol.
Also do notice that the delimiter is still in it's place.
Output
Count of tokens = 3
I want this sentence to be split into this form, but how to do.
So if anyone can help,
that will be great
Code
import java.lang.*;
public class HelloWorld {
public static void main(String[] args) {
String str = "I want this sentence to be split into this form, but how to do. So if anyone can help, that will be great";
//String delimiters = "\\s+|,\\s*|\\.\\s*";
String delimiters = "(?<=,)";
// analyzing the string
String[] tokensVal = str.split("(?<=([,.!?;~])+)(?!\\s*(but|and|if))");
// prints the number of tokens
System.out.println("Count of tokens = " + tokensVal.length);
for (String token: tokensVal) {
System.out.println(token);
}
}
}

.replace to replace input letters with symbols

I want to make everything the user enters capitalized and certain letters to be replaced with numbers or symbols. Im trying to utilize .replace but something is not going right. Im not sure what im doing wrong?
public class Qbert
{
public static void main(String[] args)
{
//variables
String str;
//get input
Scanner kb = new Scanner(System.in);
System.out.print(" Please Enter a Word:");
//accept input
str = kb.nextLine();
System.out.print("" );
System.out.println(str.toUpperCase()//make all letters entered uppercase
//sort specific letters to make them corresponding number, letter, or symbol
+ str.replace("A,#")+ str.replaceChar("E","3")+ str.replaceChar ("G","6")
+ str.replaceChar("I","!")+ str.replaceChar("S","$")+ str.replaceChar ("T","7"));
}
}
In Java, Strings are immutable. This means that modifying a string will result in a new string. E.g.
str.replace("a", "b");
this will replace all the occurrences of 'a' to 'b' in a new string. Original string will remain unaffected. So, to apply the formatting on the actual string, we will have to write:
str = str.replace("a", "b");
Similarly, if we want to do multiple replacements then, we need to append replace calls together, e.g.
str = str.replace("a","b").replace("c", "d");
Going by this, if you want to perform the substitution, the last system.out in your code will be:
System.out.println(str.toUpperCase().replace("A","#").replace("E","3")
.replace("G","6").replace("I","!").replace("S","$").replace("T","7"));
String doesn't have a replaceChar method. You probably wanted to use method replace.
And String.replace() takes 2 arguments:
public String replace(CharSequence target, CharSequence replacement)
Replaces each substring of this string that matches the literal target
sequence with the specified literal replacement sequence. The
replacement proceeds from the beginning of the string to the end, for
example, replacing "aa" with "b" in the string "aaa" will result in
"ba" rather than "ab".
You have written str.replace("A,#")+... instead of str.replace("A","#")+..., and so on
One more thing - use a good IDE like Eclipse or Intellij IDEA, they will highlight the parts of your code where you have errors.
public static void main(String... args) {
// variables
String str;
// get input
Scanner kb = new Scanner(System.in);
System.out.print(" Please Enter a Word:");
// accept input
str = kb.nextLine();
System.out.print("");
System.out.println(str.toUpperCase()); // Upper Case
System.out.println(str.toUpperCase().replace("A", "#").replace("E", "3")
.replace("E", "3").replace("G", "6").replace("I", "!").replace("S", "$").replace("T", "7") );
}
This should work like you want it to. Hope you find this helpful.
As you want to make multiple changes to the same string, you just use
str.toUpperCase().replace().replace().... This means you are giving
the output of str.toUpperCase() to the first replace function and so
on...
System.out.println(str.toUpperCase()
.replace("A","#")
.replace("E","3")
.replace("G","6")
.replace("I","!")
.replace("S","$")
.replace("T","7"));

How to replace part of a String in Java?

Im trying to replace part of a String based on a certain phrase being present within it. Consider the string "Hello my Dg6Us9k. I am alive.".
I want to search for the phase "my" and remove 8 characters to the right, which removes the hash code. This gives the string "Hello. I am alive." How can i do this in Java?
You could achieve this through string.replaceAll function.
string.replaceAll("\\bmy.{8}", "");
Add \\b if necessary. \\b called word boundary which matches between a word character and a non-word character. .{8} matches exactly the following 8 characters.
To remove also the space before my
System.out.println("Hello my Dg6Us9k. I am alive.".replaceAll("\\smy.{8}", ""));
This should do it:
String s = ("Hello my Dg6Us9k. I am alive");
s.replace(s.substring(s.indexOf("my"), s.indexOf("my")+11),"");
That is replacing the string starts at "my" and is 11 char long with nothing.
Use regex like this :
public static void main(String[] args) {
String s = "Hello my Dg6Us9k. I am alive";
String newString=s.replaceFirst("\\smy\\s\\w{7}", "");
System.out.println(newString);
}
O/P :
Hello. I am alive
Java strings are immutable, so you cannot change the string. You have to create a new string. So, find the index i of "my". Then concatenate the substring before (0...i) and after (i+8...).
int i = s.indexOf("my");
if (i == -1) { /* no "my" in there! */ }
string ret = s.substring(0,i);
ret.concat(s.substring(i+2+8));
return ret;
If you want to be flexible about the hash code length, use the folowing regexp:
String foo="Hello my Dg6Us9k. I am alive.";
String bar = foo.replaceFirst("\\smy.*?\\.", ".");
System.out.println(bar);

Deal with apostrophe in java regex in replaceALL

Trying the replace only the EXACT & WHOLE OCCURRENCES of pattern using the following code. Apparently you in you'll is being replaced as ###'ll. But what I want is only you to be replaced.
Please suggest.
import java.util.*;
import java.io.*;
public class Fielreadingtest{
public static void main(String[] args) throws IOException {
String MyText = "I knew about you long before I met you. I also know that you’re an awesome person. By the way you’ll be missed. ";
String newLine = System.getProperty("line.separator");
System.out.println("Before:" + newLine + MyText);
String pattern = "\\byou\\b";
MyText = MyText.replaceAll(pattern, "###");
System.out.println("After:" + newLine +MyText);
}
}
/*
Before:
I knew about you long before I met you. I also know that you’re an awesome person. By the way you’ll be missed.
After:
I knew about ### long before I met ###. I also know that ###’re an awesome person. By the way ###’ll be missed.
*/
This being said I have an input file which contains a list of words that I want to skip which looks like this:
Now as per #Anubhav I have to use (^|\\s)you([\\s.]|$) to replace exactly you but not anything else. Is my best bet to use a tool like notepad++ and pre & post fix all my input words as above or change something in the code itslef. The code I'm using is this:
for (String pattern : patternsToSkip) {
line = line.replaceAll(pattern, "");
}
source: https://www.cloudera.com/content/cloudera-content/cloudera-docs/HadoopTutorial/CDH4/Hadoop-Tutorial/ht_wordcount2_source.html?scroll=topic_7_1
You can instead use this regex:
String pattern = "(^|\\s)you([\\s.,;:-]|$)";
This will match "you" only at:
start or preceded by a space
end or followed by a space OR a some listed punctuation characters
You can use a negative lookahead:
\b(you)(?!['’])
Escaped for a Java string:
"\\b(you)(?!['’])"
Your demo input contains a different apostrophe than on my keyboard. I've put both in the negative lookahead.
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
<P>{#code java ReplaceYouWholeWordWithAtAtAt}</P>
**/
public class ReplaceYouWholeWordWithAtAtAt {
public static final void main(String[] ignored) {
String sRegex = "\\byou(?!['’])";
String sToSearch = "I knew about you long before I met you. I also know that you’re an awesome person. By the way you’ll be missed.";
String sRplcWith = "###";
Matcher m = Pattern.compile(sRegex).matcher(sToSearch);
StringBuffer sb = new StringBuffer();
while(m.find()) {
m.appendReplacement(sb, sRplcWith);
}
m.appendTail(sb);
System.out.println(sb);
}
}
Output:
[C:\java_code\]java ReplaceYouWholeWordWithAtAtAt
I knew about ### long before I met ###. I also know that youÆre an awesome person. By the way youÆll be missed.

How to change characters of a string into '*'

So I'm trying to make a simple Wheel of fortune type game. But I'm having a serious issue getting started. I'm just trying to convert my phrase into "*" so that it can't be seen until the user guesses what one of the letters is. Here's what I have so far:
public class Puzzle
{
private String solution="DOG PILE";
private StringBuilder puzzle;
public Puzzle(String solution)
{
int startindex=puzzle.indexOf(solution);
puzzle.replace(startIndex, endIndex, "-");
}
}
Use a regular expression and replace method:
String hideSolution = solution.replaceAll(".", "-");
Use guava library
example:
String noDigits = CharMatcher.JAVA_DIGIT.replaceFrom(string, "*"); // star out all digits
You can try something like this
public static String hide(String data, StringBuilder charactersToShow) {
return data.replaceAll("[^\\s" + charactersToShow.toString() + "]", "*");
}
public static void main(String[] args) throws Exception {
StringBuilder gueses = new StringBuilder();
String solution = "DOG PILE";
System.out.println(hide(solution, gueses));//
gueses.append('D');
System.out.println(hide(solution, gueses));
gueses.append('I');
System.out.println(hide(solution, gueses));
}
Output:
*** ****
D** ****
D** *I**
Little explanation:
replaceAll method takes two arguments: regular expression that describes what part of String should be replaced, and second argument is replacement. Result of that method is new String so original String will not be changed.
As regular expression I used class of characters [] with negation [^...] so it will match any character that is not in this class. Besides user characters I added \\s at the beginning, because it represents every white space (normal spaces, tabulators, new lines, and so on) since you probably don't want to replace them with *.
You may also want to add ' into that "set" if you don't want to replace it.

Categories