Removing space from Java string doesn't work - java

String input = "c_Name == V-GE-DO50 OR c_Name == V-GE-DO-C";
I have tried
input.replaceAll(" ", "");
input.trim();
Both did not remove white space from the string
Want the string to look like
c_Name==V-GE-DO50ORc_Name==V-GE-DO-C
Thanks

Note that the String methods return a new String with the transformation applied. Strings are immutable - i.e. they can't be changed. So it's a common mistake to do:
input.trim();
and you should instead assign a variable:
String output = input.trim();

Following works fine for me:
String input = "c_Name == V-GE-DO50 OR c_Name == V-GE-DO-C";
input = input.replaceAll(" ", "");
System.out.println(input);
Output
c_Name==V-GE-DO50ORc_Name==V-GE-DO-C
Strings are immutable, I strongly suspect you are not assigning the string again after replaceAll (or) trim();
One more thing, trim doesn't remove spaces in middle, it just removes spaces at end.

input.replaceAll("\s","") should do the trick
http://www.roseindia.net/java/string-examples/string-replaceall.shtml

String input = "c_Name == V-GE-DO50 OR c_Name == V-GE-DO-C";
input = input.replaceAll(" ", "");
System.out.println(input);
Result:
c_Name==V-GE-DO50ORc_Name==V-GE-DO-C
However, replaceAll takes Regular Expression as input value (for replacement) and this case covers getting rid of spaces in variable.
So, if you want to simply get rid of spaces in your String, use input = input.replace(" ", "") to be more efficient.

Related

Remove/Replace the part of string value

I have to remove the words from the given string.
Example :
Input:
"H|013450107776|10/15/2019
D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00|PAYMENT FOR SERVICE|Successful"
Output:
"H|013450107776|10/15/2019
D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00|Successful"
Note:"PAYMENT FOR SERVICE" is a dynamic string value it can be any thing.
I have tried using replace() and regex function but i am not able to get the exact output.
The following code will work.
public static String replace(String original, String toRemove) {
Arrays.stream(original.split("\\|"))
.filter(s -> !(s.equals(toRemove)))
.collect(Collectors.joining("|"));
}
First, create a Stream of Strings (Stream<String>) that are originally separated by |.
Second, filter them, so only Strings that are not equal to toRemove remain in the Stream.
Thrid, collect using joining with a joining character |.
Splitting your string on "|" and assuming the word you want to replace is always at the same position, the below does what you need :
String s = "H|013450107776|10/15/2019D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00|PAYMENT FOR SERVICE|Successful";
String result = s.replace(s.split("\\|")[8], "");
System.out.println(result);
It prints out :
H|013450107776|10/15/2019D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00||Successful
Here is a trick I like to use:
String input = "H|013450107776|10/15/2019D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00|PAYMENT FOR SERVICE|Successful";
System.out.println(input);
input = "|" + input + "|";
String output = input.replaceFirst("\\|PAYMENT FOR SERVICE\\|", "|");
output = output.substring(1, output.length()-1);
System.out.println(output);
To see how this works, consider the following input:
A|B|C
Let's say that we want to remove A. We first form the string:
|A|B|C|
Then, we replace |A| with just |, to give:
|B|C|
Finally, we strip those initial added pipe separators to give:
B|C
String str = "H|013450107776|10/15/2019D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00|PAYMENT FOR SERVICE|Successful";
System.out.println(str.replaceAll("PAYMENT FOR SERVICE|", ""));`
public static void main(String[] args) {
String str = "H|013450107776|10/15/2019D|0000TXN001|10/15/2019|013450107806|LCUATADA05|1000.00|PAYMENT FOR SERVICE|Successful";
String scut = "PAYMENT FOR SERVICE";
System.out.println(str.substring(0,str.indexOf(scut)) + str.substring(str.indexOf(scut)+scut.length()+1,str.length()));
}
replace all uppercase words between || with "|"
for example: "|A G G SLG SD GSD G|" -> "|"
input.replaceAll("\\|[A-Z\\s]+\\|","|")
\\s - any whitespace symbol
A-Z - symbols between A and Z
more info : https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

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:

How to split a string twice and add it to a linked list?

I tried to split a string and added it to a linked list. Each node in the linked list is a polynomial boundary. I tried this but it gave me a dangling meta character exception, what did I do wrong?
String s = "X^2+3x+5";
LinkedList p_list = new LinkedList();
s.toLowerCase();
s.replace("*x", "x");
s.replace("x^", "x");
s.replaceAll("--","+");
s.replaceAll("+-", "-");
s.replaceAll(" ", "");
String [] st = s.split("(?=[+-])");
String [] st2 = new String[2];
for(int i=0;i<=st.length;i++){
if(st[i].contains("x")){
st2=st[i].split("x");
if(st2[0].length()== 0 && st2[1].length()== 0){
p_list.addFirst(1,1);
}else if(st2[0].length()== 1 && st2[1].length()== 0){
p_list.addFirst(Integer.parseInt(st2[0]),0);
}
} else {
p_list.addFirst(Integer.parseInt(st2[0]),Integer.parseInt(st2[1]));
}
}
p_list.printList();
replace accepts a String, but replaceAll accepts a regex, and a regex that begins with + is invalid. You have two options:
escape the character +, in Java it's \\+
use Pattern#quote
Important note: String is immutable, you should assign the result to a new String.
The stack trace is pretty self-explanatory:
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta
character '+' near index 0
+-
^
You need to escape the + symbol in the following line:
s = s.replaceAll("\\+-", "-"); // Note: you need to assign the result back to 's'
Not the answer (you already got 2 of them) but very important to note that String is immutable so the manipulation methods (e.g. toLowerCase, replace etc..) will produce a new string and will not modify the String object on which they are called so assign the result to your string in order for the changes to be in effect, i.e:
s = s.toLowerCase();
First of all String is immutable, so:
String s = "X^2+3x+5";
s.toLowerCase();
s.replaceAll(....)
s.substring(etc ...)
Will give you same String as declared at the beginning. The replaceAll() method takes a regex as the first parameter. And the "*" has special meaning in a regex. You will need to escape it with \.
String result = s.toLowerCase().replaceAll("\\*x", "x")
.replace("x^", "x").replaceAll("--", "+")
.replaceAll("\\+-", "-").replaceAll("\\+-", "-")
.replaceAll(" ", "");

How to replace \ with . in java String

I want to replace \ with . in String java.
Example src\main\java\com\myapp\AppJobExecutionListener
Here I want to get like src.main.java.com.myapp.AppJobExecutionListener
I tried str.replaceAll("\\","[.]") and str.replaceAll("\\","[.]") but it is not working.
I am still getting original string src\main\java\com\myapp\AppJobExecutionListener
String is immutable in Java, so whatever methods you invoke on the String object are not reflected on it unless you reassign it.
String s = "ABC";
s.replaceAll("B","D");
System.out.println(s); //still prints "ABC"
s = s.replaceAll("B","D");
System.out.println(s); //prints "ADC"
Currently you're using replaceAll, which takes regular expression patterns. That makes life much more complicated than it needs to be. Unless you're trying to use regular expressions, just use String.replace instead.
In fact, as you're only replacing one character with another, you can just use character literals:
String replaced = original.replace('\\', '.');
The \ is doubled as it's the escape character in Java character literals - but as the above doesn't use regular expressions, the period has no special meaning.
Assign it back to string str variable, .String#replaceAll doesn't changes the string itself, it returns a new String.
str = str.replaceAll("\\\\",".")
Can you try this:
String original = "Some text with \\ and rest of the text";
String replaced = original.replace("\\",".");
System.out.println(replaced);
'\' character is doubled in a string like '\\'. So '\\' character should be used to replace it with '.' character and also using replace instead of replaceAll would be enough to make it. Here is a sample;
public static void main(String[] args) {
String myString = "src\\main\\java\\com\\vxl\\appanalytix\\AppJobExecutionListener";
System.out.println("Before Replaced: " + myString);
myString = myString.replace("\\", ".");
System.out.println("After Replaced: " + myString);
}
This will give you:
Before Replaced: src\main\java\com\vxl\appanalytix\AppJobExecutionListener
After Replaced: src.main.java.com.vxl.appanalytix.AppJobExecutionListener
With String replaceAll(String regex, String replacement):
str = str.replaceAll("\\\\", ".");
With String replace(char oldChar, char newChar):
str = str.replace('\\', '.');
With String replace(CharSequence target, CharSequence replacement)
str = str.replace("\\", ".");
String replaced = original.replace('\', '.');
try this its works well
Use replace instead of replaceall
String my_str="src\\main\\java\\com\\vxl\\appanalytix\\AppJobExecutionListener";
String my_new_str = my_str.replace("\\", ".");
System.out.println(my_new_str);
DEMO AT IDEONE.COM
replaceAll takes a regex as the first parameter.
To replace the \ you need to double escape. You need an additional \ to escape the first . And as it is a regex input you need to escape those again. As other answers have said string is immutable so you will need to assign the result
String newStr = str.replaceAll("\\\\", ".");
The second parameter is not regex so you can just put . in there but note you need four slashes to replace one backslash if using replaceAll
i tried this:
String s="src\\main\\java\\com\\vxl\\appanalytix\\AppJobExecutionListener";
s = s.replace("\\", ".");
System.out.println("s: "+ s);
output: src.main.java.com.vxl.appanalytix.AppJobExecutionListener
Just change the line to
str = str.replaceAll("\\",".");
Edit : I didnt try it, because the problem here is not whether its a correct regex,but the problem here is that he is not assigning the str to new str value. Anyways regex corrected now.

How to replace comma (,) with a dot (.) using java

I am having a String str = 12,12
I want to replace the ,(comma) with .(Dot) for decimal number calculation,
Currently i am trying this :
if( str.indexOf(",") != -1 )
{
str.replaceAll(",","\\.");
}
please help
Your problem is not with the match / replacement, but that String is immutable, you need to assign the result:
str = str.replaceAll(",","."); // or "\\.", it doesn't matter...
Just use replace instead of replaceAll (which expects regex):
str = str.replace(",", ".");
or
str = str.replace(',', '.');
(replace takes as input either char or CharSequence, which is an interface implemented by String)
Also note that you should reassign the result
str = str.replace(',', '.')
should do the trick.
if(str.indexOf(",")!=-1) { str = str.replaceAll(",","."); }
or even better
str = str.replace(',', '.');
Just use str.replace(',', '.') - it is both fast and efficient when a single character is to be replaced. And if the comma doesn't exist, it does nothing.
For the current information you are giving, it will be enought with this simple regex to do the replacement:
str.replaceAll(",", ".");
in the java src you can add a new tool like this:
public static String remplaceVirguleParpoint(String chaine) {
return chaine.replaceAll(",", "\\.");
}
Use this:
String str = " 12,12"
str = str.replaceAll("(\\d+)\\,(\\d+)", "$1.$2");
System.out.println("str:"+str); //-> str:12.12
hope help you.
If you want to change it in general because you are from Europe and want to use dots instead of commas for reading an input with a scaner you can do it like this:
Scanner sc = new Scanner(System.in);
sc.useLocale(Locale.US);
System.out.println(sc.locale().getDisplayCountry());
Double accepted with comma instead of dot

Categories

Resources