Change all letters except space from a string using Java - java

I want to change all letters from a string to "-" char except space using Java.
I tried:
String out = secretWord.replaceAll("^ " , "-");
and
String out = secretWord.replaceAll("\\s" , "-");
They didn't work.
I tried:
String newWord = secretWord.replaceAll("[A-Z]" , "-");
It worked but i didn't change Turkish characters I use in that string.
Original Code:
public class ChangeToLine {
public static void main(String[] args) {
String originalWord = "ABİDİKUŞ GUBİDİKUŞ";
String secretWord = originalWord;
}
}

You can use the \\S regex:
String s = "Sonra görüşürüz";
String replaced = s.replaceAll("\\S", "-");
System.out.println(replaced); // outputs ----- ---------

Use a character class
String out = secretWord.replaceAll("[^ ]" , "-");
or a capital S, instead of a lower s to replace all non space chars
String out2 = secretWord.replaceAll("\\S" , "-");

NOT needs to be expressed in square brackets in java.util.regex.Pattern:
String out = secretWord.replaceAll("[^\\s]", "-")

Related

Why is the replace all method not working?

I am testing out the replaceAll() method of the String class and I am having problems with it.
I do not understand why my code does not replace whitespaces with an empty string.
Here's my code:
public static void main(String[] args) {
String str = " I like pie!#!#! It's one of my favorite things !1!!!1111";
str = str.toLowerCase();
str = str.replaceAll("\\p{Punct}", "");
str = str.replaceAll("[^a-zA-Z]", "");
str = str.replaceAll("\\s+", " ");
System.out.print(str);
}
Output:
ilikepieitsoneofmyfavoritethings
The problem is there are no whitespaces in your String after this:
str = str.replaceAll("[^a-zA-Z]", "");
which replaces all characters that are not letters, which includes whitespaces, with a blank (effectively deleting it).
Add whitespace to that character class so they don't get nuked:
str = str.replaceAll("[^a-zA-Z\\s]", "");
And this line may be deleted:
str = str.replaceAll("\\p{Punct}", "");
because it's redundant.
Final code:
String str = " I like pie!#!#! It's one of my favorite things !1!!!1111";
str = str.toLowerCase();
str = str.replaceAll("[^a-zA-Z\\s]", "");
str = str.replaceAll("\\s+", " ");
System.out.print(str);
Output:
i like pie its one of my favorite things
You may want to add str = str.trim(); to remove the leading space.

String replaceAll not replacing i++;

String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i++;", "");
// Desired output :: newCode = "helloworld";
But this is not replacing i++ with blank.
just use replace() instead of replaceAll()
String preCode = "helloi++;world";
String newCode = preCode.replace("i++;", "");
or if you want replaceAll(), apply following regex
String preCode = "helloi++;world";
String newCode = preCode.replaceAll("i\\+\\+;", "");
Note : in the case of replace() the first argument is a character sequence, but in the case of replaceAll the first argument is regex
try this one
public class Practice {
public static void main(String...args) {
String preCode = "Helloi++;world";
String newCode = preCode.replace(String.valueOf("i++;"),"");
System.out.println(newCode);
}
}
The problem is the string that you are using to replace , that is cnsidered as regex pattern to skip the meaning you will have to use escape sequence like below.
String newCode = preCode.replaceAll("i\\+\\+;", "");

How to replace or convert the first occurrence of a dot from a string in java

Example:
Input
Str = P.O.Box
Output
Str= PO BOX
I can able to convert the string to uppercase and replace all dot(.) with a space.
public static void main(String args[]){
String s = "P.O.Box 1836";
String uppercase = s.toUpperCase();
System.out.println("uppercase "+uppercase);
String replace = uppercase.replace("."," ");
System.out.println("replace "+replace);
}
System.out.print(s.toUpperCase().replaceFirst("[.]", "").replaceAll("[.]"," "));
If you look the String API carefully, you would notice that there's a methods that goes by:-
replaceFirst(String regex, String replacement)
Hope it helps.
You have to use the replaceFirst method twice. First for replacing the . with <nothing>. Second for replacing the second . with a <space>.
String str = "P.O.Box";
str = str.replaceFirst("[.]", "");
System.out.println(str.replaceFirst("[.]", " "));
This one liner should do the job:
String s = "P.O.Box";
String replace = s.toUpperCase().replaceAll("\\.(?=[^.]*\\.)", "").replace('.', ' ');
//=> PO BOX
String resultValue = "";
String[] result = uppercase.split("[.]");
for (String value : result)
{
if (value.toCharArray().length > 1)
{
resultValue = resultValue + " " + value;
}
else
{
resultValue = resultValue + value;
}
}
Try this
System.out.println("P.O.Box".toUpperCase().replaceFirst("\\.","").replaceAll("\\."," "));
Out put
PO BOX
NOTE: \\ is needed here if you just use . only your out put will blank.
Live demo.
You should use replaceFirst method twice.
String replace = uppercase.replace("\\.", "").replaceFirst("\\.", "");
As you want to remove the first dot and replace the second one with a space, you need replace the whole P.O. section
Use
replace("P\\.O\\.", "PO ");

String modification in java

Hi i am having string like " MOTOR PRIVATE CAR-PACKAGE POLICY " . Now i want remove last two words and add hyphen between words finally i want string like " MOTOR-PRIVATE-CAR' . I tried many times using string methods in java but could not find exactly. Can anyone give a solution for that . Give me a code is plus for me.
Thanks in advance
public class StringModify {
public static void main(String[] args) {
try {
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
System.out.println("Value-------------------->"+value.replaceFirst("\\s*\\w+\\s+\\w+$", ""));
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can do it with the help of substring() and replaceAll() methods
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
value = value.substring(0, value.indexOf("-")); //get the string till -
value = value.replaceAll("\\s", "-"); //replace all the space chars with -
System.out.println(value);
I have used String.replaceAll() instead of String.replace() to use the regex for white space
\s stands for white space character and and while adding it as regex, we need to escape it with an extra \ so --> \\s
indexOf("-") method returns the index of first occurrence of the String passed, which should be the 2nd parameter to substring method, which is the endIndex
You can do it in two steps:
To get all the words from the string before "-", you can use String
substring and indexOf methods.
To replace empty spaces with hiphen(-), you can use the String replace method.
Here is the code:
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
value = value.substring(0,value.indexOf("-")); // get the words before "-"
value = value.replace(" ", "-"); // replace space with hiphen
System.out.println(value);
public class StringModify {
/**
* #param args
*/
public static void main(String[] args) {
try {
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
System.out.println("Value-------------------->"+value.replaceFirst("\\s*\\w+\\s+\\w+$", ""));
value = value.substring(0,value.indexOf("-")); // get the words before "-"
value = value.replace(" ", "-"); // replace space with hiphen
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can split the string with '-' which gives you the part of the string in which you need to insert ' '. Split the string again with ' ' and insert '-' b/w the words.
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
String[] phrase = value.split("-");
String[] words = phrase[0].split(" ");
String newValue;
for(int i = 0; i < words.length; i++)
newValue += words[i] + "-";
String var = "/";
String query = "INSERT INTO Recieptnumbersetup VALUES('"+Prestring+"' '"+var+"','"+var+"' '"+post string+"')" ;
PS = connection.PrepareStatement(query);
Use this i have used slash over here i was having same problem.

removing space before new line in java

i have a space before a new line in a string and cant remove it (in java).
I have tried the following but nothing works:
strToFix = strToFix.trim();
strToFix = strToFix.replace(" \n", "");
strToFix = strToFix.replaceAll("\\s\\n", "");
myString.replaceAll("[ \t]+(\r\n?|\n)", "$1");
replaceAll takes a regular expression as an argument. The [ \t] matches one or more spaces or tabs. The (\r\n?|\n) matches a newline and puts the result in $1.
try this:
strToFix = strToFix.replaceAll(" \\n", "\n");
'\' is a special character in regex, you need to escape it use '\'.
I believe with this one you should try this instead:
strToFix = strToFix.replace(" \\n", "\n");
Edit:
I forgot the escape in my original answer. James.Xu in his answer reminded me.
Are you sure?
String s1 = "hi ";
System.out.println("|" + s1.trim() + "|");
String s2 = "hi \n";
System.out.println("|" + s2.trim() + "|");
prints
|hi|
|hi|
are you sure it is a space what you're trying to remove? You should print string bytes and see if the first byte's value is actually a 32 (decimal) or 20 (hexadecimal).
trim() seems to do what your asking on my system. Here's the code I used, maybe you want to try it on your system:
public class so5488527 {
public static void main(String [] args)
{
String testString1 = "abc \n";
String testString2 = "def \n";
String testString3 = "ghi \n";
String testString4 = "jkl \n";
testString3 = testString3.trim();
System.out.println(testString1);
System.out.println(testString2.trim());
System.out.println(testString3);
System.out.println(testString4.trim());
}
}

Categories