whitespace will not get removed - java

Assume there is a url="www.example.com/". Using the following code I want to remove the trailing slash but it leaves a blank at the end of string (which by the way I do not know why) and using the rest of the code, I am trying to remove the white space but it will not work.
String url="http://www.example.com/";
int slash=url.lastIndexOf("/");
StringBuilder myURL = new StringBuilder(url);
if(url.endsWith("/")){
myURL.setCharAt(slash, Character.MIN_VALUE );
url=myURL.toString();
}
url=url.replaceAll("\\s+","");
System.out.println(url);

Try to trim it: url = url.trim();

Because \s+ does not match Character.MIN_VALUE. Use ' ' instead.
String url="www.example.com/";
int slash=url.lastIndexOf("/");
StringBuilder myURL = new StringBuilder(url);
if(url.endsWith("/")){
myURL.setCharAt(slash, ' ');
url=myURL.toString();
}
url=url.replaceAll("\\s+","");
System.out.println(url);
But why don't you just remove the / ?
String url="www.example.com/";
int slash=url.lastIndexOf("/");
StringBuilder myURL = new StringBuilder(url);
myURL.deleteCharAt(slash);
System.out.println(myURL);

String url="www.example.com/";
if(url.endsWith("/")){
url = url.substring(0, url.length()-1);
}
System.out.println(url);

Instead of setCharAt() you should use deleteCharAt().
But the simplest way to do the job is
String url="www.example.com/";
url = url.substring(0, url.lastIndexOf("/"));

The issue appears to be the use of the setCharAt method.
This method replaces a char with another char. So even though you have replaced it with the Character.MIN_VALUE which at first glance may appear to represent the literal Null it is actually still a unicode character ('\0000' aka the null character).
The simplest fix would be to replace...
myURL.setCharAt(slash, Character.MIN_VALUE );
with...
myURL.deleteCharAt(slash);
Further info regarding the null character...
Understanding the difference between null and '\u000' in Java
what's the default value of char?
This is my first answer so apologies if I've not kept to conventions.

I think the empty space is caused by Character.MIN_VALUE being interpreted as a space.
Try this. Its a little cleaner than your current replace code and will leave no space.
if(url.endsWith("/")){
url = url.trim().substring(0, url.length-1);
}

Replace you code inside your if-block with the below one
url = url.substring(0, url.length()-1).trim();
Then I hope you will no longer need that StringBuilder object also.
So your final code will look like
String url="www.example.com";
url = (url.endsWith("/")) ? url.substring(0, url.length()-1) : url;
System.out.print(url);

Why are you complicating things, if this can be achieved in single line
String url="www.example.com/";
url=url.replace("/","");
System.out.println(url);

Related

Dynamically replace part in URL using Regex

I tried searching for something similar, and couldn't find anything. I'm having difficulty trying to replace a few characters after a specific part in a URL.
Here is the URL: https://scontent-b.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/s130x130/10390064_10152552351881633_355852593677844144_n.jpg?oh=479fa99a88adea07f6660e1c23724e42&oe=5519DE4B
I want to remove the /v/ part, leave the t1.0-9, and also remove the /s130x130/.I cannot just replace s130x130, because those may be different variables. How do I go about doing that?
I have a previous URL where I am using this code:
if (pictureUri.indexOf("&url=") != -1)
{
String replacement = "";
String url = pictureUri.replaceAll("&", "/");
String result = url.replaceAll("().*?(/url=)",
"$1" + replacement + "$2");
String pictureUrl = null;
if (result.startsWith("/url="))
{
pictureUrl = result.replace("/url=", "");
}
}
Can I do something similar with the above URL?
With the regex
/v/|/s\d+x\d+/
replaced with
/
It turns the string from
https://scontent-b.xx.fbcdn.net/hphotos-xpf1/v/t1.0-9/s130x130/10390064_10152552351881633_355852593677844144_n.jpg?oh=479fa99a88adea07f6660e1c23724e42&oe=5519DE4B
to
https://scontent-b.xx.fbcdn.net/hphotos-xpf1/t1.0-9/10390064_10152552351881633_355852593677844144_n.jpg?oh=479fa99a88adea07f6660e1c23724e42&oe=5519DE4B
as seen here. Is this what you're trying to do?

How to replace ' with empty string in Java

How can I replace single quote ' with empty string in Java. I tried following but doesn't seem to be working.
String data="Sid's den";
data.replace("'", "");
data.replaceAll("'", "");
Thanks in advance. Any help is much appreciated.(Output should be: Sids den)
Thanks guys for your responses. I guess I should have been more clear about my question. Basically I am getting special characters from the table and with what value we have to replace that also from the same table. Here is snippet of the code:
query = "select spl_char, replace_with from entcon_splchars";
ptsmt = DBConnector.sqlConnection.prepareStatement(query);
rs = ptsmt.executeQuery();
while (rs.next()) {
if(data.contains(rs.getString("spl_char"))){
data = data.replace(rs.getString("spl_char"),rs.getString("replace_with"));
}
}
so whenevr in the data we have special character ' then I am facing nullpointer exception. Please suggest how to go ahead with this?
Use replace, no need for regex.
Remember that Strings are immutable, so you need to assign data.replace("'", ""); to a variable.
For instance: data = data.replace("'", "");
Strings are immutable so you'll receive a new instance. Try
data = data.replace("'", "");
Your Edit
Check the return values of getString() - you could get your NPE because your database table contains null values in one of the columns spl_char or replace_with.
I can see your problem, If you need to replace it you need to replace it and also need to assign it back to the variable. Solution should be,
String data="Sid's den";
data = data.replaceAll("'", "");
System.out.println(data);
Because String is immutable in java. But StringBuffer and StringBuilder is mutable in java.
String
StringBuffer
StringBuilder
Just try with:
"foo'bar'buz".replace("'", "")
Output:
"foobarbuz"
In your case:
String data = "Sid's den";
String output = data.replace("'", "");
Try:
data = data.replace ("'", "") ;
OR
data = data.replaceAll("'", "") ;
You would need to assign the replaced string to a variable.

ReplaceAll Method

I want to replace "\" with this "/" in my string.
I am using method replaceAll for this. But it is giving me error.
String filePath = "D:\pbx_u01\apache-tomcat-6.0.32\bin\uploadFiles\win.jpg";
String my_new_str = filePath.replaceAll("\\", "//");
Just use replace.
The method replaceAll takes a regular expression and yours would be malformed.
String filePath = "D:/pbx_u01/apache-tomcat-6.0.32/bin/uploadFiles/win.jpg";
System.out.println(filePath.replace("/", "\\"));
Output
D:\pbx_u01\apache-tomcat-6.0.32\bin\uploadFiles\win.jpg
When you absolutely want to use regex for this, use:
String filePath = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg";
String my_new_str = filePath.replaceAll("\\\\", "/");
Output of my_new_str would be:
D:/pbx_u01/apache-tomcat-6.0.32/bin/uploadFiles/win.jpg
Just be sure to notice the double backslashes \\ in the source String (you used single ones \ in your question.)
But Mena showed in his answer a much simpler, more readable way to achive the same. (Just adopt the slashes and backslashes)
You are unable because character '//' should be typed only single '/'.
String filePath = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg"
String my_new_str = filePath.replaceAll("\\", "/");
Above may be fail during execution giving you a PatternSyntaxException, because the first String is a regular expression so you use this,
String filePath = "D:\\pbx_u01\\apache-tomcat-6.0.32\\bin\\uploadFiles\\win.jpg"
String my_new_str = filePath.replaceAll("\\\\", "/");
Check this Demo ideOne

Need to Trim Java String

I need help in trimming a string url.
Let's say the String is http://myurl.com/users/232222232/pageid
What i would like returned would be /232222232/pageid
Now the 'myurl.com' can change but the /users/ will always be the same.
I suggest you use substring and indexOf("/users/").
String url = "http://myurl.com/users/232222232/pageid";
String lastPart = url.substring(url.indexOf("/users/") + 6);
System.out.println(lastPart); // prints "/232222232/pageid"
A slightly more sophisticated variant would be to let the URL class parse the url for you:
URL url = new URL("http://myurl.com/users/232222232/pageid");
String lastPart = url.getPath().substring(6);
System.out.println(lastPart); // prints "/232222232/pageid"
And, a third approach, using regular expressions:
String url = "http://myurl.com/users/232222232/pageid";
String lastPart = url.replaceAll(".*/users", "");
System.out.println(lastPart); // prints "/232222232/pageid"
string.replaceAll(".*/users(/.*/.*)", "$1");
String rest = url.substring(url.indexOf("/users/") + 6);
You can use split(String regex,int limit) which will split the string around the pattern in regex at most limit times, so...
String url="http://myurl.com/users/232222232/pageid";
String[] parts=url.split("/users",1);
//parts={"http://myurl.com","/232222232/pageid"}
String rest=parts[1];
//rest="/232222232/pageid"
The limit is there to prevent strings like "http://myurl.com/users/232222232/users/pageid" giving answers like "/232222232".
You can use String.indexOf() and String.substring() in order to achieve this:
String pattern = "/users/";
String url = "http://myurl.com/users/232222232/pageid";
System.out.println(url.substring(url.indexOf(pattern)+pattern.length()-1);

Problem in replacing special characters in a String in java

I got a String as response from server which is like the below:
hsb:\\\10.217.111.33\javap\Coventry\
Now I want to parse this string in such a way that I need to replace all \ with /.
Also I need to remove the first part of the String which is hsb:\\\
So, my resultant string should be of like this :
10.217.111.33/javap/coventry/
Can anyone help me by providing sample java code for this problem.
Here you have a "dirty" startup "solution":
String s = "hsb:\\\\\\10.217.111.33\\javap\\Coventry\\";
String w = s.replace('\\', '/');
String x = w.replace("hsb:///", "");
String result = yourString.substring(7);
result = result.replaceAll("\\\\", "/");

Categories

Resources