Remove backslashes in string - java

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.

Related

Parse out specific characters from java string

I have been trying to drop specific values from a String holding JDBC query results and column metadata. The format of the output is:
[{I_Col1=someValue1, I_Col2=someVal2}, {I_Col3=someVal3}]
I am trying to get it into the following format:
I_Col1=someValue1, I_Col2=someVal2, I_Col3=someVal3
I have tried just dropping everything before the "=", but some of the "someVal" data has "=" in them. Is there any efficient way to solve this issue?
below is the code I used:
for(int i = 0; i < finalResult.size(); i+=modval) {
String resulttemp = finalResult.get(i).toString();
String [] parts = resulttemp.split(",");
//below is only for
for(int z = 0; z < columnHeaders.size(); z++) {
String replaced ="";
replaced = parts[z].replace("*=", "");
System.out.println("Replaced: " + replaced);
}
}
You don't need any splitting here!
You can use replaceAll() and the power of regular expressions to simply replace all occurrences of those unwanted characters, like in:
someString.replaceAll("[\\[\\]\\{\\}", "")
When you apply that to your strings, the resulting string should exactly look like required.
You could use a regular expression to replace the square and curly brackets like this [\[\]{}]
For example:
String s = "[{I_Col1=someValue1, I_Col2=someVal2}, {I_Col3=someVal3}]";
System.out.println(s.replaceAll("[\\[\\]{}]", ""));
That would produce the following output:
I_Col1=someValue1, I_Col2=someVal2, I_Col3=someVal3
which is what you expect in your post.
A better approach however might be to match instead of replace if you know the character set that will be in the position of 'someValue'. Then you can design a regex that will match this perticular string in such a way that no matter what seperates I_Col1=someValue1 from the rest of the String, you will be able to extract it :-)
EDIT:
With regards to the matching approach, given that the value following I_Col1= consists of characters from a-z and _ (regardless of the case) you could use this pattern: (I_Col\d=\w+),?
For example:
String s = "[{I_Col1=someValue1, I_Col2=someVal2}, {I_Col3=someVal3}]";
Matcher m = Pattern.compile("(I_Col\\d=\\w+),?").matcher(s);
while (m.find())
System.out.println(m.group(1));
This will produce:
I_Col1=someValue1
I_Col2=someVal2
I_Col3=someVal3
You could do four calls to replaceAll on the string.
String query = "[{I_Col1=someValue1, I_Col2=someVal2}, {I_Col3=someVal3}]"
String queryWithoutBracesAndBrackets = query.replaceAll("\\{", "").replaceAll("\\]", "").replaceAll("\\]", "").replaceAll("\\[", "")
Or you could use a regexp if you want the code to be more understandable.
String query = "[{I_Col1=someValue1, I_Col2=someVal2}, {I_Col3=someVal3}]"
queryWithoutBracesAndBrackets = query.replaceAll("\\[|\\]|\\{|\\}", "")

Replace parts of a string in Java

I need to replace parts of a string by looking up the System properties.
For example, consider the string It was {var1} beauty killed {var2}
I need to parse the string, and replace all the words contained within the parenthesis by looking up their value in System properties. If System.getProperty() returns null, then simply replace with empty character. This is pretty straightforward when I know the variables well ahead. But the string that I need to parse is not defined ahead. I wouldn't know how many number of variables are in the string and what the variable names are. Assuming a simple, well formatted string (no nested parenthesis, open - close matches), what is the simplest or the most elegant way to parse through the string and replace all the character sequences that are enclosed in the parenthesis?
Only solution I could come up with is to traverse the string from the first character, note down the positions of the start and end positions of the parenthesis, replace the string between them, and then continue until reaching the end of the string. Is there simpler way to do this?
You can use the parentheses to break the initial string into substrings, and then replace every other substring.
String[] substituteValues = {"the", "str", "other", "another"};
int substituteValuesIndex = 0;
String test = "Here is {var1} string called {var2}";
// split the string up into substrings
test = test.replaceAll("\\}", "\\{");
String[] splitString = test.split("\\{");
// now sub in your values
for (int k=1; k < splitString.length; k = k+2) {
splitString[k] = substituteValues[substituteValuesIndex];
substituteValuesIndex++;
}
String result = "";
for (String s : splitString) {
result = result + s;
}

Java: Next character in String

I have one String generated of random characters that will encrypt another String given by the user by adding the first character from the String with the first character of the given String. It's working fine, but if the user were to enter multiple words with spaces in between, I want to choose the next character of the first String rather than code the space itself. Is that possible? This is what I have:
(random is the coded string and sentenceUpper is string given by user)
public static void encrypt(String sentenceUpper){
String newSentence = "";
for(int i = 0; i < sentenceUpper.length(); i++){
char one = random.charAt(i);
char two = sentenceUpper.charAt(i);
if(one < 'A' || one > 'Z'){
two = sentenceUpper.charAt(1 + i);}
char result = (char)((one + two)%26 + 'A');
newSentence += "" + result;
}
EDIT FOR BETTER EXPLANATION:
I have:
String random = "WFAZYZAZOHS";
I would like to code user input:
String upperCase: "YOU GO";
So, I'm going to take Y + L = U, etc...
to get :
"UTUSEN
"
But I see that there's a space in "YOU GO" , So I'd like to change it to:
WFA ZY + YOU GO = UTU SE.
I hope that's better explained.
The simplest way to do this would probably be to use an if statement to run the code in the loop only if the character is not a space. If you don't want to skip the character in the random string, you would need a separate variable to track the current character index in that string.
Example: Put this after defining one and two and put the rest of the loop inside it:
if(two==' '){
...
}
Then, add the space in the output:
else{
newSentence+=" ";
}

Formatting String Array efficiently in Java

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.

How to remove the degrees celsius symbol from a string (java)

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.

Categories

Resources