removing white spaces from string value - java

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
}

Related

How to insert quotes inside parenthesis using a regex

I have a string of SVG markup that contains multiples of these:
url(#586-xr___83_193_101__rgba_243_156_18_1__0-rgba_243_156_18_1__100)
and I need them to be like this:
url('#586-xr___83_193_101__rgba_243_156_18_1__0-rgba_243_156_18_1__100')
with quotes inside the parenthesis.
These will be mixed inside a long string containing lots of different markup, so needs to be very accurate.
You can use a regex like this:
\((.*?)\)
With the replacement string ('$1')
The idea is capture everything within parentheses and concatenates the '
So, you can use a code like this:
String str = "url(#586-xr___83_193_101__rgba_243_156_18_1__0-rgba_243_156_18_1__100)";
str = str.replaceAll("\\((.*?)\\)", "('$1')");
//Outuput: url('#586-xr___83_193_101__rgba_243_156_18_1__0-rgba_243_156_18_1__100')
IdeOne example
In case you want a better performance regex you can use:
str = str.replaceAll("\\(([^)]*)\\)", "('$1')");
ReplaceAll remove a part of the string and put an unrelated and invariant new stuff instead.
Because the replacement string can't be the same at both side, the only solution I imagine (with the constraint of using RegEx and ReplaceAll) is to do it in two time:
String Str = "url(#586-xr___83_193_101__rgba_243_156_18_1__0-rgba_243_156_18_1__100)";
Str = Str.replaceAll("\\(", "('"); // replace left parenthesis
Str = Str.replaceAll("\\)", "')"); // replace right parenthesis
System.out.print("Return Value: " + Str);
// Return Value: url('#586-xr___83_193_101__rgba_243_156_18_1__0-rgba_243_156_18_1__100')
You can test it here.

Need help on String Trimming Java

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+$", "");

Split by space but not newline

I am trying to convert all links in a given string to clickable a tags using the following code :
String [] parts = comment.split("\\s");
String newComment=null;
for( String item : parts ) try {
URL url = new URL(item);
// If possible then replace with anchor...
if(newComment==null){
newComment=""+ url + " ";
}else{
newComment=newComment+""+ url + " ";
}
} catch (MalformedURLException e) {
// If there was an URL that was not it!...
if(newComment==null){
newComment = item+" ";
}else{
newComment = newComment+item+" ";
}
}
It works fine for
Hi there, click here http://www.google.com ok?
converting it to
Hi there, click here http://www.google.com ok?
But when the string is this :
Hi there, click
here http://www.google.com
ok?
its still converting it to :
Hi there, click here http://www.google.com ok?
Whereas I want the final result to be :
Hi there, click
here http://www.google.com
ok?
I think its including the newline character also while making the split.
How do I preserve the newline character in this case ?
I would suggest a different approach:
String noNewLines = "Hi there, click here http://www.google.com ok?";
String newLines = "Hi there, \r\nclick here \nhttp://www.google.com ok?";
// This is a String format with two String variables.
// They will be replaced with the desired values once the "format" method is called.
String replacementFormat = "%s";
// The first round brackets define a group with anything starting with
// "http(s)". The second round brackets delimit that group by a lookforward reference
// to whitespace.
String pattern = "(http(s)?://.+?)(?=\\s)";
noNewLines = noNewLines.replaceAll(
pattern,
// The "$1" literals are group back-references.
// In our instance, they reference the group enclosed between the first
// round brackets in the "pattern" String.
new Formatter().format(replacementFormat, "$1", "$1")
.toString()
);
System.out.println(noNewLines);
System.out.println();
newLines = newLines.replaceAll(
pattern,
new Formatter().format(replacementFormat, "$1", "$1")
.toString()
);
System.out.println(newLines);
Output:
Hi there, click here http://www.google.com ok?
Hi there,
click here
http://www.google.com ok?
This will replace all your http(s) links to an anchor reference, whether or not you have newlines (windows or *nix) in your text.
Edit
For best coding practices you should set the replacementFormat and pattern variables as constants (so, final static String REPLACEMENT_FORMAT and so on).
Edit II
Actually grouping the URl pattern isn't really necessary, as the whitespace lookahead is sufficient. But well, I'm leaving it as is, it works.
You could just use
String [] parts = comment.split("\\ ");
instead of
String [] parts = comment.split("\\s");
as eldris said, "\s" is for every white-space character, so "\ ", for just the space character itself should do for you.
I would suggest following solution to your problem:
First split by new line character
For each line do processing that you have mentioned above
Add all processed lines
That ways new line character will be retained and also you will be able to do in each line what you are currently doing.
Hope this helps.
Cheers !!

Manipulating a String using .substring in Java

I'm reading line by line from a text file which contains a string followed by a white space followed by another string. It's the second string I want to use for my method.
Example of text file:
0h e3ne6t
ie 51b0x
6 8qlaqi
ty2 9j5dbb
nwz55 7lrwor
So I want 'e3ne6t', then '51b0x' etc.
I've tried using the .substring method and have tried using " " and "\s" as representations of white space.
Here's a snippet of code that should give you a good idea of what I'm trying to achieve.
while ((strLine = br.readLine()) != null) {
lineNumber++;
System.out.println("lineNumber = " + lineNumber);
int index = strLine.indexOf(" "); // tried \\s
System.out.println("index = " + index);
strLine.substring(index);
System.out.println(strLine);
if (myString.equals(strLine)) {
System.out.println("Match Found!");;
System.out.println("myString = " + myString );
System.out.println("strLine =" + strLine);
}
}
I even tried changing the white space to a "+" but it still wouldn't work.
Suggestions?
substring doesn't change the contents of the string you call it on - nothing does, as String is immutable in Java. Instead, it returns a new string which is the relevant substring. So you can use:
strLine = strLine.substring(index);
(The same is true for things like toUpperCase, trim, replace etc.)
String's are immutable in java. you need to reassign the value retrieved by substring to the actual variable.
strLine=strLine.substring(index);
Also note that indexOf(str) doesn't take regex, so indexOf("\\s") would give you nothing.
As others have mentioned, Strings are immutable in Java. The substring method returns a new String that is the substring. But if you pass index to substring, then you will get a substring starting with your space character, e.g. " e3ne6t". So I would use this:
strLine = strLine.substring(index + 1);
to get your second field, advancing past the space character, as long as index is not -1 (not found).
Manipulating a String using .substring in Java
www.gleegrid.com/all_in_one/language/substring

How do I delete specific characters from a particular String in Java?

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..

Categories