Java how to replace backslash? [duplicate] - java

This question already has answers here:
String replace a Backslash
(8 answers)
Closed 6 years ago.
In java, I have a file path, like 'C:\A\B\C', I want it changed to ''C:/A/B/C'. how to replace the backslashes?

String text = "C:\\A\\B\\C";
String newString = text.replace("\\", "/");
System.out.println(newString);

Since you asked for a regular expression, you'll have to escape the '\' character several times:
String path = "c:\\A\\B\\C";
System.out.println(path.replaceAll("\\\\", "/"));

You can do this using the String.replace method:
public static void main(String[] args) {
String foo = "C:\\foo\\bar";
String newfoo = foo.replace("\\", "/");
System.out.println(newfoo);
}

String oldPath = "C:\\A\\B\\C";
String newPath = oldPath.replace('\\', '/');

To replace all occurrences of a given character :
String result = candidate.replace( '\\', '/' );
Regards,
Cyril

Related

Using backslash (\) inside a String variable in java [duplicate]

This question already has answers here:
What is the backslash character (\\)?
(6 answers)
Closed last year.
I am not able to get the message value in the desired format.
String url = "sample"
String message ="/test{\"url\":"' + url + '\"}
The desired value of message is "/test{\"url\":\"sample\"}"
Any idea on this?
Try with this:
String url = "sample";
String message ="/test{\\\"url\\\":\""+url+"\\\"}";
Or you can use String.format:
String url = "sample";
String message = String.format("/test{\\\"url\\\":\"%s\\\"}",url);
Try the following syntax:
String url = "sample";
String message ="/test{\\\"url\\\":\"" + url + "\\\"}";
Please note that back-slash \ and double-quote " are specialized character and hence they need to be escaped using back-slash \.
Hence, \\ is used for \ and \" is used for " in String literal.
Output:
/test{\"url\":"sample\"}
After several tried, I found the solution:
StringBuilder sb=new StringBuilder();
sb.append("\"/test{");
sb.append("\"\\");
sb.append("\"");
sb.append("url\\\"");
sb.append(":");
sb.append("\\\"");
sb.append(url);
sb.append("\"\\}\"");
System.out.println(sb.toString());

How To Parse String In Java With * [duplicate]

This question already has answers here:
How do I split a string in Java?
(39 answers)
Closed 2 years ago.
I have a string like this.
PER*IP**TE**1234567890*EM*sampleEmail#Email.com
How can I parse the string into multiple lines like this in Java?
PER
IP
TE
//Empty String
EM
1234567890
sampleEmail#Email.com
You could use a regex replacement:
String input = "PER*IP**TE*1234567890*EM*sampleEmail#Email.com";
String output = input.replaceAll("\\*", "\n");
System.out.println(output);
This prints:
PER
IP
TE
1234567890
EM
sampleEmail#Email.com
You can use String#split. Since * is a regular expression metacharacter, you need to escape it with a backslash or use Pattern#quote.
Arrays.stream("PER*IP**TE**1234567890*EM*sampleEmail#Email.com".split(Pattern.quote("*")))
.forEach(System.out::println);
String newstring = string.replace("*", "\n");
System.out.println(newstring);
now if you don't want that the empty line show up, use this:
String string = "PER*IP**TE**1234567890*EM*sampleEmail#Email.com"
String newstring = string.replaceAll("\\*+","*").replace("*", "\n");
System.out.println(newstring);

Replacing multiple substrings from a string in Java/Android [duplicate]

This question already has answers here:
Java Replacing multiple different substring in a string at once (or in the most efficient way)
(11 answers)
Closed 6 years ago.
Example:
String originalString = "This is just a string folks";
I want to remove(or replace them with "") : 1. "This is" , 2. "folks"
Desired output :
finalString = "just a string";
For a sole substring it's easy, we can just use replace/replaceAll.
I also know it works for various numeric values replace("[0-9]","")
But can that be done for characters?
You can create a function like below:
String replaceMultiple (String baseString, String ... replaceParts) {
for (String s : replaceParts) {
baseString = baseString.replaceAll(s, "");
}
return baseString;
}
And call it like:
String finalString = replaceMultiple("This is just a string folks", "This is", "folks");
You can pass multiple strings that are to be replaced after the first parameter.
It works like this:
String originalString = "This is just a string folks";
originalString = originalString.replace("This is", "");
originalString = originalString.replace("folks", "");
//originalString is now finalString

Replace dash character in Java String [duplicate]

This question already has answers here:
Java String replace not working [duplicate]
(6 answers)
Closed 9 years ago.
I tried to replace "-" character in a Java String but is doesn't work :
str.replace("\u2014", "");
Could you help me ?
String is Immutable in Java. You have to reassign it to get the result back:
String str ="your string with dashesh";
str= str.replace("\u2014", "");
See the API for details.
this simply works..
String str = "String-with-dash-";
str=str.replace("-", "");
System.out.println(str);
output - Stringwithdash
It's quite easy. You can use an Apache library, that will be useful while you develop an application. This is apache-commons-lang. You can do the following:
public class Main {
public static void main(String[] args) {
String test = "Dash - string";
String withoutDash = StringUtils.replace(test, "-", "");
System.out.println(withoutDash);
}
}

Replace Last Occurrence of a character in a string [duplicate]

This question already has answers here:
Replace the last part of a string
(11 answers)
Closed 5 years ago.
I am having a string like this
"Position, fix, dial"
I want to replace the last double quote(") with escape double quote(\")
The result of the string is to be
"Position, fix, dial\"
How can I do this. I am aware of replacing the first occurrence of the string. but don't know how to replace the last occurrence of a string
This should work:
String replaceLast(String string, String substring, String replacement)
{
int index = string.lastIndexOf(substring);
if (index == -1)
return string;
return string.substring(0, index) + replacement
+ string.substring(index+substring.length());
}
This:
System.out.println(replaceLast("\"Position, fix, dial\"", "\"", "\\\""));
Prints:
"Position, fix, dial\"
Test.
String str = "\"Position, fix, dial\"";
int ind = str.lastIndexOf("\"");
if( ind>=0 )
str = new StringBuilder(str).replace(ind, ind+1,"\\\"").toString();
System.out.println(str);
Update
if( ind>=0 )
str = new StringBuilder(str.length()+1)
.append(str, 0, ind)
.append('\\')
.append(str, ind, str.length())
.toString();
If you only want to remove the las character (in case there is one) this is a one line method. I use this for directories.
localDir = (dir.endsWith("/")) ? dir.substring(0,dir.lastIndexOf("/")) : dir;
String docId = "918e07,454f_id,did";
StringBuffer buffer = new StringBuffer(docId);
docId = buffer.reverse().toString().replaceFirst(",",";");
docId = new StringBuffer(docId).reverse().toString();

Categories

Resources