I am getting this string from Db
str = "External - Internal ";
I want to remove the last whitespace from the string. I have already tried string.trim() and assigned it to another string
Kindly suggest as this is just not working. below is my code for reference.
public static void main(String args[]){
String str = "External - Internal ";
String temp = str.trim();
System.out.println("1"+temp);
temp=str.replaceAll(" ", "");
System.out.println("2"+temp);
temp=str.replace("\\r", "");
System.out.println("3"+temp);
}
Regards
Abhi
You could do this simply through string.replaceAll or string.replaceFirst function.
string.replaceAll("\\s(?=\\S*$)", "");
If you exactly mean the space which was at the end then use the below regex.
string.replaceAll("\\s$", "");
Use \\s+ instead of \\s if you want to deal with one or more spaces.
You can find your answer here Strip Leading and Trailing Spaces From Java String
Look at the top two answers. Try right trim as myString.replaceAll("\s+$", "");
Related
Im trying to replace part of a String based on a certain phrase being present within it. Consider the string "Hello my Dg6Us9k. I am alive.".
I want to search for the phase "my" and remove 8 characters to the right, which removes the hash code. This gives the string "Hello. I am alive." How can i do this in Java?
You could achieve this through string.replaceAll function.
string.replaceAll("\\bmy.{8}", "");
Add \\b if necessary. \\b called word boundary which matches between a word character and a non-word character. .{8} matches exactly the following 8 characters.
To remove also the space before my
System.out.println("Hello my Dg6Us9k. I am alive.".replaceAll("\\smy.{8}", ""));
This should do it:
String s = ("Hello my Dg6Us9k. I am alive");
s.replace(s.substring(s.indexOf("my"), s.indexOf("my")+11),"");
That is replacing the string starts at "my" and is 11 char long with nothing.
Use regex like this :
public static void main(String[] args) {
String s = "Hello my Dg6Us9k. I am alive";
String newString=s.replaceFirst("\\smy\\s\\w{7}", "");
System.out.println(newString);
}
O/P :
Hello. I am alive
Java strings are immutable, so you cannot change the string. You have to create a new string. So, find the index i of "my". Then concatenate the substring before (0...i) and after (i+8...).
int i = s.indexOf("my");
if (i == -1) { /* no "my" in there! */ }
string ret = s.substring(0,i);
ret.concat(s.substring(i+2+8));
return ret;
If you want to be flexible about the hash code length, use the folowing regexp:
String foo="Hello my Dg6Us9k. I am alive.";
String bar = foo.replaceFirst("\\smy.*?\\.", ".");
System.out.println(bar);
Please have a look at the below code
public class PuctuationRemover {
public PuctuationRemover()
{
String str = ":The red; third.fox is hungry!!! but, is he angry? doesn't! (yeah!). Call 911! system. can't access it! what the , hell . is this. people of my country, really? 123465 can^be,found.... OK . you got it? ";
String str2 = str.replaceAll("[^a-zA-Z'\\s]+", str);
System.out.println(str2);
}
public static void main(String[]args)
{
new PuctuationRemover();
}
}
The expected output is
The red thirdfox is hungry but is he angry doesn't yeah Call system can't access it what the hell is this people of my country really canbefound OK you got it
The output I get is
:The red; third.fox is hungry!!! but, is he angry? doesn't! (yeah!). Call 911! system. can't access it! what the , hell . is this. people of my country, ..............
The original working regex is here.
What has gone wrong here?
If you need to remove the punctuation, supply an empty string as the second argument instead of the original string itself. The second argument to replaceAll is not the original string, but what to replace the match with. Change
String str2 = str.replaceAll("[^a-zA-Z'\\s]+", str);
with
String str2 = str.replaceAll("[^a-zA-Z'\\s]+", "");
Use String str2 = str.replaceAll("[^a-zA-Z'\\s]+", "");
You are doing String str2 = str.replaceAll("[^a-zA-Z'\\s]+", str); .You are replacing the whole original String.
Please see this javadoc for more on String replaceAll.
Here in public String replaceAll(String regex, String replacement) second argument, i.e replacement is the string to be substituted for each match.
Note: Its better to catch PatternSyntaxException .
You're replacing your old string with your old string, which means you keep the same string even after replacing it. What you need to do is replace all of the characters specified in the regex with a no-character "".
EDIT: Darn, you people are fast typers! =P
So I'm playing around string manipulation. I'm done replacing white space characters with hyphens. Now I want to combine replacing white spaces characters and removing apostrophe from string. How can I do this?
This is what I've tried so far:
String str = "Please Don't Ask Me";
String newStr = str.replaceAll("\\s+","-");
System.out.println("New string is " + newStr);
Output is:
Please-Don't-Ask-Me
But I want the output to be:
Please-Dont-Ask-Me
But I can't get to work removing the apostrophe. Any ideas? Help is much appreciated. Thanks.
Try this:
String newStr = str.replaceAll("\\s+","-").replaceAll("'", "");
The first replaceAll returns the String with all spaces replaced with -, then we perform on this another replaceAll to replace all ' with nothing (Meaning, we are removing them).
It's very easy, use replaceAll again on the resulted String:
String newStr = str.replaceAll("\\s+","-").replaceAll("'","");
Try this..
String s = "This is a string that contain's a few incorrect apostrophe's. don't fail me now.'O stranger o'f t'h'e f'u't'u'r'e!";
System.out.println(s);
s = s.replace("\'", "");
System.out.println("\n"+s);
i have a link http://localhost:8080/reporting/pvsUsageAction.do?form_action=inline_audit_view&days=7&projectStatus=scheduled&justificationId=5&justificationName= No Technicians in Area in my struts based web application.
The variable in URL justificationName have some spaces before its vales as shown. when i get value of justificationName using request.getParameter("justificationName") it gives me that value with spaces as given in the URL. i want to remove those spaces. i tried trim() i tries str = str.replace(" ", ""); but any of them did not removed those spaces. can any one tell some other way to remove the space.
Noted one more thing that i did right click on the link and opened the link into new tab there i noticed that link looks like.
http://localhost:8080/reporting/pvsUsageAction.do?form_action=inline_audit_view&days=7&projectStatus=scheduled&justificationId=5&justificationName=%A0%A0%A0%A0%A0%A0%A0%A0No%20Technicians%20in%20Area
Notable point is that in the address bar it shows %A0 for white spaces and also show %20 for space as well see the link and tell the difference please if any one have idea about it.
EDIT
Here is my code
String justificationCode = "";
if (request.getParameter("justificationName") != null) {
justificationCode = request.getParameter("justificationName");
}
justificationCode = justificationCode.replace(" ", "");
Note: replace function remove the space from inside the string but not removing starting spaces.
e-g if my string is " This is string" after using replace it becomes " Thisisstring"
Thanks in advance
Strings are immutable in Java, so the method doesn't change the string you pass but returns a new one. You must use the returned value :
str = str.replace(" ", "");
Manual trim
You need to remove the spaces the string. This will remove any number of consecutive spaces.
String trimmed = str.replaceAll(" +", "");
If you want to replace all whitespace characters:
String trimmed = str.replaceAll("\\s+", "");
URL Encoding
You could also use an URLEncoder, which sounds like a more appropriate way to go:
import java.net.UrlEncoder;
String url = "http://localhost:8080/reporting/" + URLEncoder.encode("pvsUsageAction.do?form_action=inline_audit_view&days=7&projectStatus=scheduled&justificationId=5&justificationName= No Technicians in Area", "ISO-8859-1");
You have to assign the result of the replace(String regex, String replacement) operation to another variable. See the Javadoc for the replace(String regex, String replacement) method. It returns a brand new String object and this is because the String(s) in Java are immutable. In your case, you can simply do the following
String noSpacesString = str.replace("\\s+", "");
You can use replaceAll("\\s","") It will remove all white space.
If you are trying to remove the trailing and ending white spaces, then
s = s.trim();
Or if you want to remove all the spaces the use :
s = s.replace(" ","");
There are two ways of doing one is regular expression based or your own way of implementing the logic
replaceAll("\\s","")
or
if (text.contains(" ") || text.contains("\t") || text.contains("\r")
|| text.contains("\n"))
{
//code goes here
}
For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).
What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.
Reassign the variable to a substring:
s = s.substring(0, s.length() - 1)
Also an alternative way of solving your problem: you might also want to consider using a StringTokenizer to read the file and set the delimiters to be the characters you don't want to be part of words.
Use:
String str = "whatever";
str = str.replaceAll("[,.]", "");
replaceAll takes a regular expression. This:
[,.]
...looks for each comma and/or period.
To remove the last character do as Mark Byers said
s = s.substring(0, s.length() - 1);
Additionally, another way to remove the characters you don't want would be to use the .replace(oldCharacter, newCharacter) method.
as in:
s = s.replace(",","");
and
s = s.replace(".","");
You can't modify a String in Java. They are immutable. All you can do is create a new string that is substring of the old string, minus the last character.
In some cases a StringBuffer might help you instead.
The best method is what Mark Byers explains:
s = s.substring(0, s.length() - 1)
For example, if we want to replace \ to space " " with ReplaceAll, it doesn't work fine
String.replaceAll("\\", "");
or
String.replaceAll("\\$", ""); //if it is a path
Note that the word boundaries also depend on the Locale. I think the best way to do it using standard java.text.BreakIterator. Here is an example from the java.sun.com tutorial.
import java.text.BreakIterator;
import java.util.Locale;
public static void main(String[] args) {
String text = "\n" +
"\n" +
"For example I'm extracting a text String from a text file and I need those words to form an array. However, when I do all that some words end with comma (,) or a full stop (.) or even have brackets attached to them (which is all perfectly normal).\n" +
"\n" +
"What I want to do is to get rid of those characters. I've been trying to do that using those predefined String methods in Java but I just can't get around it.\n" +
"\n" +
"Every help appreciated. Thanx";
BreakIterator wordIterator = BreakIterator.getWordInstance(Locale.getDefault());
extractWords(text, wordIterator);
}
static void extractWords(String target, BreakIterator wordIterator) {
wordIterator.setText(target);
int start = wordIterator.first();
int end = wordIterator.next();
while (end != BreakIterator.DONE) {
String word = target.substring(start, end);
if (Character.isLetterOrDigit(word.charAt(0))) {
System.out.println(word);
}
start = end;
end = wordIterator.next();
}
}
Source: http://java.sun.com/docs/books/tutorial/i18n/text/word.html
You can use replaceAll() method :
String.replaceAll(",", "");
String.replaceAll("\\.", "");
String.replaceAll("\\(", "");
etc..