Java String(Query String) manipulation - java

I have a strange scenario. Query string has value first=second=12123423423423432323234
String queryString = request.getParameter("first=second=12123423423423432323234")
So i have to:
capture 'first' and 'second' values
validate the query string has 'first' and 'second'.
Could someone please share how I can achieve this in the best possible way?
I really appreciate your help on this.

I believe your query string should look like
first=firstvalue&second=secondvalue
You can use this in your servlet to print the query string
String firstValue = request.getParameter("first");
String secondValue = request.getParameter("second");
System.out.println("Query String:first="+firstValue+"second=+"secondValue);
In your case, where the query string is
first=second=12123423423423432323234
You could do this
String first = request.getParameter("first");
String second = request.getParameter("second");
if(first.contains("second=")){
second = first.split("second=")[1];
first = first.split("second=")[0];
}
out.println("[First:"+first+"][Second:"+second+"]");

If your parameters are separated properly by & (i.e. first=&second=something), then simply .getParameter("first") and .getParameter("second")
Otherwise, you'd need to play with the string - probably split around =, and for the value of first cut until second is encountered. Though I fail to see how will that work if first has a value: first=foosecond=bar?

Related

How to insert certain values ​into a string in certain part

I have a special table in my database where I store the message key - value in the form, for example: question first - How are you, ...?
Now I want to insert for example a name at the end of the question. I don't need a hardcode, I want to do it through some formatting. I know that there is an option to insert text through % or ?1 - but I don't know how to apply this in practice. How are you, % or (?1)?
And what if I need to insert text not only at the end, but also in the random parts:
Hey, (name)! Where is your brother, (brothers name)?
You can insert a String into another String using the String.format() method. Place a %s anywhere in the String where you want and then follow the below syntax. More information here.
String original = "Add to this pre-existing String";
String newString = String.format("Add %s to this pre-existing String", "words");
// original = "Add to this pre-existing String"
// newString = "Add words to this pre-existing String"
In your specific situation, you can store the names as other Strings and do this:
String name = "anyName";
String brothers_name = "anyBrotherName";
String formattedString = String.format("Hey, %s! Where is your brother, %s?", name, brothers_name);
How about this?
String.format("Hey, %s! Where is your brother, %s?","Sally", "Johnny");
For using the %, first you will need to create another variable of type string in which you store the text you want to print.
Example:
String a="Alice";
String b="Bob";
String str=string.format("Hey, %s! Where is your brother, %s?"a,b);
System.out.println(str);
Output:
Hey Alice! Where is your brother, Bob?
You can get more information about this here

refactoring Java to get string length

I am starting out with Java and trying to find a neat way of refactoring the below code so that I can set the firstName variable as a string and in the same line get and set the firstNameLength string length as an integer.
String firstName = "Boris";
int firstNameLength = firstName.length();
I have been trying variations of the below code but to no avail!
int newAge = String firstName = "Boris".length();
You can't declare 2 new variables, but assignment of firstName is possible.
String firstName;
int newAge = (firstName = "Boris").length();
(You could put both in the same line).
I doubt however, that anyone would consider this more readable than
String firstName = "Boris";
int newAge = firstName.length();
and there are no other benefits.
There's no way you can delcare two variables of different type in one statement.
So you're stuck with 2 statements anyway. So you could put it in one line like this:
String name; int length = (name= "Boris").length();
But really, what's the point?
I guess if you want to make your code more streamlined, you should think about why you need an extra variable holding the length in the first place - as this can always be computed later. So you keep redundant information.
Actually another solution would be to use StringUtils in the following way:
int length = StringUtils.length("Boris");
But this comes with the Apache Common package.

Java - split string into an array

I have this code
String speed_string = "baka baka saka laka";
String[] string_array = speed_string.split(" ");
System.out.println(string_array.length);
and it returns the value of 1 when I run it. Why is that? It seems as if only the first word of the string gets saved.
Use \\s and update the code as below
String speed_string = "baka baka saka laka";
String[] string_array = speed_string.split("\\s");
System.out.println(string_array.length);
Most probably what you think is space (ASCII decimal 32) is not (in your input string).
That would explain perfectly the behavior you're seeing.

Working with stringtokenizers and numbers

Using the second StringTokenizer constructor, write a method that
returns either the first or second token in the input string based on
the token argument. You will need to set custom delimiters which are
enclosed in a string but not separated by commas.
okay, so this is what i have so far..... i need help making the code so that it returns either the first or the second token depending on the users input.... right now i only know how to return either the first or the second token. ive tried making a while or and if statement but it always says i cant convert int to string, ive even tried type casting but it wouldnt let me do that either.... what can i do to make it return whichever token the user inputs?
String parseEqn_p2(String input, int token) {
StringTokenizer st = new StringTokenizer(input, "+-/*%");
String first = st.nextToken();
String second = st.nextToken();
return first ;
""it always says i cant convert int to string," - Use String.valueOf(int)
You probably want something like this
if (first.eqauls(String.valueOf(token)) {
return first;
} else if (...) {
}
return null; // if not found
...
Note : you may also need to .trim() the token, depending on what the input is. If there are spaces, the tokenizer won't exclude them, so you would need to call .trim() on the String first before trying to compare. like
String first = st.nextToken().trim();
Also, it looks like you may want to use a character class, because what you're doing is looking using a single delimiter of all the characters, which isn't what you want. Try this instead
StringTokenizer st = new StringTokenizer(input, "[+-/*%]");
In for any case you wanted the method to return an int, then you would need to parse the token
int first = Integer.parseInt(st.nextToken());
Also, NOTE: Whoever gave you this assignment, ask them to read the documentation for StringTokenizer, where you'll find this excerpt
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
The following example illustrates how the String.split method can be used to break up a string into its basic tokens:
String[] result = "this is a test".split("\\s");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);

ResultSet How to get String from an object when data is null?

In my Oracle table there are columns with different type.
I want to read all columns as number.
String str = resultSet.getString("col1");
The problem is that if column in database is defined as number, and value is
0.5
the returned string will be
.5
I can not use any other getter like getDecimal() and etc.
If I use:
String str = resultSet.getObject("col1").toString();
I'll get an exception if the value is null.
You could use
String str = String.valueOf(resultSet.getObject("col1"));
as a simple workaround to avoid any exceptions. (Not sure why you can't use resultSet.getDouble("col1") though.)
If you don't want to see an empty string rather than the literal "null" for a null value (which is what String.valueOf()) will produce, you can use:
Object value = resultSet.getObject("col1")
String str = value == null ? "" : value.toString();

Categories