Replace method doesn't work properly - java

Hello I have a string and when I try to use replace method in for loop it doesn't work
String phrase="hello friend";
String[] wordds=phrase.split(" ");
String newPhrase="sup friendhello weirdo";
for (int g=0;g<2;g++)
{
finalPhrase+=newPhrase.replace(wordds[g],"");
}
System.out.println(finalPhrase);
It prints out sup hello weirdo and I expect it to print sup weirdo.
What am I doing wrong?

Let's debug it together.
wordds = ["hello", "friend"].
newPhrase = "sup friendhello weirdo".
Then you're running on some g from 0 to 1 (Should be from 0 to wordds.length.
newPhrase.replace(wordds[g],""); will indeed replace as you want, but when you debug your program, you'll notice that you are using += instead of:
newPhrase=newPhrase.replace(wordds[g],"");
Tip for life: use the debugger, it's there to help you.

Try this:
String phrase = "hello friend";
String[] wordds = phrase.split(" ");
String newPhrase = "sup friendhello weirdo";
for (int g = 0; g < 2 ; g++) {
newPhrase = newPhrase.replace(wordds[g], "");
}
System.out.println(newPhrase);
===================================================
updated
few things that you need to correct
you need to remove concat oprator (+), when you try to replace particular word in a sentence. Just assign it after replacing
for each time you enter the loop you are taking the initial declared string, instead you need to use the string which is getting updated each time

what are you doing, is keep append the replaced Phrase to another one
newPhrase = newPhrase.replace(wordds[g],"");

Apart from the suggestions of an immediate fix, you can also consider a regex-based solution, with no loops:
String phrase="hello friend";
String regex=phrase.replace(' ', '|');
String newPhrase="sup friendhello weirdo";
String finalPhrase=newPhrase.replaceAll(regex,"");
System.out.println(finalPhrase);
or, more succinctly:
System.out.println("sup friendhello weirdo"
.replaceAll("hello friend".replace(' ','|'),
""));

This should do the trick:
String phrase="hello friend";
String[] wordds=phrase.split(" ");
String newPhrase="sup friendhello weirdo";
String finalPhrase=newPhrase;
for (int g=0;g<wordds.length;g++)
{
finalPhrase=finalPhrase.replace(wordds[g],"");
}
System.out.println(finalPhrase);
First you assign finalPhrase to your newPhrase. Then you iterate over all split words (i've changed your magic constant 2 into number of split words wordds.length. Every word will be replaced in the finalPhrase string. The resulting string looks like sup weirdo (it has two spaces between words).
You can clean extra spaces using the answer from here:
System.out.println(finalPhrase.trim().replaceAll(" +", " "));

Related

How to remove a trailing comma from a string (Java)

I have an array, which I use a for each loop to iterate through. I then store it in a string and then try to add a comma to it, but am struggling look for a "logic" based solution.
I am almost close to about 1 year's worth of Java under my belt, so most of the solutions I am trying to find to implement are mostly logic based (for now), since this is apart of Java MOOC's course. What are some options I can look at? What am I missing?
for(int number: array){
String thread = "";
thread += number + ", ";
System.out.print(thread);
}
You can use a Stream to achieve this result.
System.out.println(Arrays.stream(array).collect(Collectors.joining(",")));
I'm not sure the constraints of this project for your course, but if you're able, try a StringJoiner! It will add a delimiter automatically to separate items that are added to it. Another note, I think you're going to want to declare your String outside of your for loop. otherwise it resets every iteration.
StringJoiner joiner = new StringJoiner(",");
for(int number : array){
joiner.add(String.valueOf(number));
}
System.out.print(joiner.toString());
What I like to do when I'm just doing something simple and quick is this:
String thread = "";
for (int i = 0; i < array.length; i++) {
int number = array[i];
thread += number;
if (i < array.length - 1) {
thread += ", ";
}
}
Basically all it does is check that we aren't on the last index and append the comma only if it isn't the last index. It's quick, simple, and doesn't require any other classes.
Pressuming you had a string ending with a comma, followed by zero or more white spaces you could do the following. String.replaceAll() uses a regular expression to detect the replacement part.
\\s* means 0 or more white spaces
$ means at the end of the line
String str = "a, a, b,c, ";
str = str.replaceAll(",\\s*$","");
Prints
a, a, b,c

Is there a way to get System.out.print(); value from a For loop;

I'm making a guess the String program game, and I need to convert the users inputted string from letters and whitespaces/spaces to question marks(?). How would I go about that?
I used a for loop and it gave me what I wanted but I can't use the output of the for loop outside the loop.
System.out.println("Please enter a string of words.");
String userString = scan.nextLine();
userString=userString.toLowerCase();
System.out.println(userString);
int s1 = userString.length();
System.out.println(s1);
for(int a=0;a<s1;a++) {
System.out.print("?");
}
I entered "this is a string" for userString.
When I run the program, it outputs:
????????????????
Is there a way to turn this output into a String?
Or is there a better way of converting String values into "?"?
There is no need to print ? for every character. You can just replace every char with a ? and generate a new string without printing.
String newUserString = userString.replaceAll(".","?");
If you want to replace every character of a String with ?, you can try
String newString = userString.replaceAll(".", "?");
The "." is a regular expression that will match any character except a newline, which your String won't contain anyway.
from what i understood it i think you want to store the "?" ,
to do that
create a string var outside the for loop
and append '?' in it.
String temp="";
for(int i=0;i<s1;i++)
{
temp=temp+"?";
}
System.out.println(temp);
this should store the string in temp.
Java 11 provides repeat() method.
You can use
“?”.repeat(s1) inside sysout
System.out.print(“?”.repeat(s1)) and can remove the for-loop
It will repeat the ? s1 times.
replace all is the correct answer, but if for some reason you HAD to do a for loop you could use StringBuilder and append a ? for each character in the string like so:
String userInput = "myString";
StringBuilder myBuilder = new StringBuilder();
for(int x = 0; x<userInput.length(); x++){
myBuilder.append("?");
}
String myNewString = myBuilder.toString();
But the replace all answers above are the right way to do it.

Replace characters and keep only one of these characters

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:

Why does System.out.println print a new line while System.out.print prints nothing?

I am having trouble with split function. I do not know how it works.
Here is my source code:
// Using println to print out the result
String str = " Welcome to Java Tutorial ";
str = str.trim();
String[] arr = str.split(" ");
for (String c : arr) {
System.out.println(c);
}
//Using print to print out the result
String str = " Welcome to Java Tutorial ";
str = str.trim();
String[] arr = str.split(" ");
for (String c : arr) {
System.out.print(c);
}
and the results are:
The first is the result when using println, the second is the result when using print,
I do not understand why space appears in println, while it does not appear in print. Can anyone explain it for me?
Since you have many spaces in your string, if you look at the output of split function, the resulted array looks like
[Welcome, , , , , , , to, , , , Java, , , , , Tutorial]
So if you look close they are empty String's "".
When you do a println("") it is printing a line with no string.
However when you do print(""), it is no more visibility of that string and it looks nothing getting printed.
If you want to separate them regardless of spaces between them, split them by white space.
Lastly, trim() won't remove the spaces within the String. It can only trim spaces in the first and last.
What you are doing is splitting by every individual white space. So for every space you have in your string, it is split as a separate string If you want to split just the words, you can use the whitespace regex:
String[] arr = str.split("\\s+");
This will fix your problem with the consecutive whitespaces you are printing.
Also, When you use print instead of println your print value DOES NOT carry over to the next line. Thus when you cann println("") you are just going to a new line.
println() method prints everything in a new line but the print() method prints everything in the same line.
So, when you are splitting your string by space(" ") then,
for the first one, the string is splitting for every space. So, every time a new line comes while printing. You can't see anything just the new line because you are printing: "" this. Because your code is:
System.out.println("");
But for the second one, the string is splitting for every space but you are using print() method that's why it's not going to the new line.
You can overcome this by regex.
You can use this regex: \\s+
So, you have to write:
String[] arr = str.split("\\s+");

Part I - Java Split String function

I am still new at java. I have this basic split string function as below. I need to capture the substrings post split. My question is how to move individually split parts into separate variables instead of printing them? Do I need another array to move them separately? Is there another simpler way to achieve this? In part I, for simplicity, I am assuming the delimiters to be spaces. Appreciate your help!
public class SplitString {
public static void main(String[] args) {
String phrase = "First Second Third";
String delims = "[ ]+";
String[] tokens = phrase.split(delims);
String first;
String middle;
String last;
for (int i = 0; i < tokens.length; i++)
{
System.out.println(tokens[i]);
//I need to move first part to first and second part to second and so on
}
}
}
array[index] accesses the indexth element of array, so
first = tokens[0]; // Array indices start at zero, not 1.
second = tokens[1];
third = tokens[2];
You should really check the length first, and if the string you're splitting is user input, tell the user what went wrong.
if (tokens.length != 3) {
System.err.println(
"I expected a phrase with 3 words separated by spaces,"
+ " not `" + phrase + "`");
return;
}
If the number of Strings that you will end up with after the split has taken place is known, then you can simply assign the variables like so.
String first = tokens[0];
String middle = tokens[1];
String last = tokens[2];
If the number of tokens is not known, then there is no way (within my knowledge) to assign each one to a individual variable.
If you're assuming that your String is three words, then it's quite simple.
String first = tokens[0];
String middle = tokens[1];
String last = tokens[2];
if(tokens.length>3)
{
String first=tokens[0];
String middle=tokens[1];
String last=tokens[2];
}
Thanks everyone...all of you have answered me in some way or the other. Initially I was assuming only 3 entries in the input but turns out it could vary :) for now i'll stick with the simple straight assignments to 3 variables until I figure out another way! Thanks.

Categories

Resources