I've been trying to remove the degree Celsius symbol from the following string for a few hours now. I've looked at prior posts and I see that /u2103 is the unicode representation for it. Despite trying to remove that string, I've still had no luck. Here's what I have now:
String temp = "Technology=Li-poly;Temperature=23.0 <degree symbol>C;Voltage=3835";
StringBuilder filtered = new StringBuilder(temp.length());
for (int i = 0; i < temp.length(); i++) {
char test = temp.charAt(i);
if (test >= 0x20 && test <= 0x7e) {
filtered.append(test);
}
}
temp = filtered.toString();
temp.replaceAll(" ", "%20");
The resulting string looks like this:
Technology=Li-poly;Temperature=23.0 C;
I've also tried
temp.replaceAll("\\u2103", "");
temp.replaceChar((char)0x2103, ' ');
But none of this works.
My current problem is that the function to filter the string leaves a blank space but the call to replaceAll(" ", "%20") doesn't seem to recognize that particular space. ReplaceAll will replace other spaces with %20.
This is one problem:
temp.replaceAll(" ", "%20");
You're calling replaceAll but never using the result. Strings are immutable - any method which looks like it's changing the content is actually returning the different string as a result. You want:
temp = temp.replaceAll(" ", "%20");
Having said that, it's not clear why you're trying to replace the space at all, nor what's wrong with your resulting string.
You've got the same problem with your other temp.replaceAll and temp.replaceChar calls.
Your attempt to replace the character directly would also fail as you're escaping the backslash - you really want:
temp = temp.replace("\u2103", "");
Note the use of replace instead of replaceAll - the latter uses regular expressions, which there's no need to use at all here.
Perhaps you could leverage the Character.isWhiteSpace() function.
Related
In my jsp page I have a dropdown list with multiple selection , and I store these values in an array of Strings using getParamterValues() , then I'm converting the array to a String that has this format: ('x','y','z'). So it can work with the IN operator of SQL server.
But the problem is that after the array is converted into a String each element is surrounded with backslashes. Like so: (\'X\',\'Z\',\'Y\').
I have used String.replaceAll("\\\\", ""); which was working fine in another Java application. I am unsure why it doesn't work with my servlet solution (web Application).
here is my code :
String[] Names = request.getParameterValues("Name");
String Name = "(";
for (int i = 0; i < Names.length; i++) {
Name += "'".concat(Names[i]).concat("'") + ',';
}
Name = Name.concat(")");
Name = Name.replace(",)", ")");
Name = Name.replaceAll("\\\\", "");
I know that Name = Name.replaceAll("\\\\", ""); will remove the backslashes but I don't know why it's not working in the servlet ?!
Is there a problem with values from the dropdown list?
Try using something like:
String[] names = request.getParameterValues("Name");
StringBuilder name = new StringBuilder("(");
for(int index = 0; index <names.length; index++){
name.append("'");
name.append(names[index].replace("\\","").replace("/",""));
name.append("'");
name.append(index != names.length -1? "," : ")");
}
String output = name.toString();
The replace() method replaces every instance of the sub string, therefore you do not have to use "\\\\" unless of course if you only want to remove the double slashes and leave the single slashes.
If the problem persists then there are two possible reasons for it.
The debugger expresses ' as \', so there should be no problem when sending the query to the server.
The \ is not actually a slash or backslash but another character that looks like as backslash. You can find which character it is by using int test = output.charAt(output.length() - 3); and then check the value of the test variable using the debugger.
I want to be able to trim one quote from each side of a java string. Here are some examples.
"foo" -> foo
"foo\"" -> foo\"
"\"foo\"" -> \"foo\"
I'm currently using StringUtils.trim from common lang but when I end the string with a escaped quote, it trims that too because they are consecutive. I want to be able to trim exactly one quote.
I ended up using org.apache.commons.lang3.StringUtils.substringBetween and it works.
You may also use the substring() method and trim the first and last characters on condition although it's a bit long.
trimedString= s.substring((s.charAt(0)=='"')?1:0 , (s.charAt(s.length()-1)=='"')?s.length()-1:s.length());
I prefer to use this String method
public String[] split(String regex)
basically if you feed in the quotation mark then you will get an array of strings holding all of the chunks between your quotation marks.
String[] parts = originalString.split("\"");
String quoteReduced = parts[0];
for (int i = 1; i < (parts.length() -1); i++){
quoteReduced = quoteReduced.concat( parts[i] +"\"" );
}
quoteReduced = quoteReduced.concat( "\"" +parts[parts.length()-1]);
While it may not be the most straight forward it is the way that I would get around this. The first piece and last piece could be included in the loop but would require an if statement.
I was working on some string formatting, and I was curious if I was doing it the most efficient way.
Assume I have a String Array:
String ArrayOne[] = {"/test/" , "/this/is/test" , "/that/is/" "/random/words" }
I want the result Array to be
String resultArray[] = {"test", "this_is_test" , "that_is" , "random_words" }
It's quite messy and brute-force-like.
for(char c : ArrayOne[i].toCharArray()) {
if(c == '/'){
occurances[i]++;
}
}
First I count the number of "/" in each String like above and then using these counts, I find the indexOf("/") for each string and add "_" accordingly.
As you can see though, it gets very messy.
Is there a more efficient way to do this besides the brute-force way I'm doing?
Thanks!
You could use replaceAll and replace, as follows:
String resultArray[] = new String[ArrayOne.length];
for (int i = 0; i < ArrayOne.length; ++i) {
resultArray[i] = ArrayOne[i].replaceAll("^/|/$", "").replace('/', '_');
}
The replaceAll method searches the string for a match to the regex given in the first argument, and replaces each match with the text in the second argument.
Here, we use it first to remove leading and trailing slashes. We search for slashes at the start of the string (^/) or the end of the string (/$), and replace them with nothing.
Then, we replace all remaining slashes with underscores using replace.
I need to have access to java source files and I am using the String's method trim() to remove any leading and trailing whitespaces. However the code which is some scope, for example:
if(name.equals("joe")){
System.out.println(name);
}
the white spaces for the printing statement are not being removed completely. Is there a way to be able to remove also these white-spaces please?
Thanks
EDIT: I did use a new variable:
String n = statements.get(i).toString().trim();
System.out.println(n);
however the output still looks like this:
System.out.println("NAME:" + m.getName());
BlockStmt bs = m.getBody();
List<Statement> statements = bs.getStmts();
for (int i = 0; i < statements.size(); i++) {
if ((statements.get(i).toString().trim().contains(needed)) & (statements.get(i).toString().trim().length() == needed.length())) {
System.out.println("HEREEEEEEEEEEEEEEEEEEEEEEEEEE");
}
}
Some of the strings are still containing the spaces beforehand
You are mistaken. The String.trim() method does remove leading and trailing whiteshape entirely.
However, I suspect that your real problem is that you don't know what this really means. Java strings are immutable, so trim() obviously doesn't modify the target String object. Instead, it returns a new String instance with the whitespace removed. So you need to use it as follows:
String trimmed = someString.trim();
You must have to assign the result of string. (String objects are immutable).
name=name.trim();
if(name.equals("joe")){
System.out.println(name);
}
As #home mentioned:
if(name.equals("joe")){
String newName = name.trim();
System.out.println(newName);
}
Should work
EDIT: I guess that you want to use trim before the condition. My mistake.
String newName = name.trim();
if(newName.equals("joe")){
System.out.println(newName);
}
I am getting response for some images in json format within this tag:
"xmlImageIds":"57948916||57948917||57948918||57948919||57948920||57948921||57948 922||57948923||57948924||57948925||57948926||5794892"
What i want to do is to separate each image id using .split("||") of the string class. Then append url with this image id and display it.
I have tried .replace("\"|\"|","\"|"); but its not working for me. Please help.
EDIT: Shabbir, I tried to update your question according to your comments below. Please edit it again, if I didn't get it right.
Use
.replace("||", "|");
| is no special char.
However, if you are using split() or replaceAll instead of replace(), beware that you need to escape the pipe symbol as \\|, because these methods take a regex as parameter.
For example:
public static void main(String[] args) {
String in = "\"xmlImageIds\":\"57948916||57948917||57948918||57948919||57948920||57948921||57948922||57948923||57948924||57948925||57948926||5794892\"".replace("||", "|");
String[] q = in.split("\"");
String[] ids = q[3].split("\\|");
for (String id : ids) {
System.out.println("http://test/" + id);
}
}
I think I know what your problem is. You need to assign the result of replace(), not just call it.
String s = "foo||bar||baz";
s = s.replace("||", "|");
System.out.println(s);
I tested it, and just calling s.replace("||", "|"); doesn't seem to modify the string; you have to assign that result back to s.
Edit: The Java 6 spec says "Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar." (the emphasis is mine).
According to http://docs.oracle.com/javase/6/docs/api/java/lang/String.html, replace() takes chars instead of Strings. Perhaps you should try replaceAll(String, String) instead? Either that, or try changing your String ("") quotation marks into char ('') quotation marks.
Edit: I just noticed the overload for replace() that takes a CharSequence. I'd still give replaceAll() a try though.
String pipe="pipes||";
System.out.println("Old Pipe:::"+pipe);
System.out.println("Updated Pipe:::"+pipe.replace("||", "|"));
i dont remember how it works that method... but you can make your own:
String withTwoPipes = "helloTwo||pipes";
for(int i=0; i<withTwoPipes.lenght;i++){
char a = withTwoPipes.charAt(i);
if(a=='|' && i<withTwoPipes.lenght+1){
char b = withTwoPipes.charAt(i+1);
if(b=='|' && i<withTwoPipes.lenght){
withTwoPipes.charAt(i)='';
withTwoPipes.charAt(i+1)='|';
}
}
}
I think that some code like this should work... its not a perfect answer but can help...