removing comma from string array - java

I want to execute a query like
select ID from "xyz_DB"."test" where user in ('a','b')
so the corresponding code is like
String s="(";
for(String user:selUsers){
s+= " ' " + user + " ', ";
}
s+=")";
Select ID from test where userId in s;
The following code is forming the value of s as ('a','b',)
i want to remove the comma after the end of array how to do this ?

Here is one way to do this:
String s = "(";
boolean first = true;
for(String user : selUsers){
if (first) {
first = false;
} else {
s += ", ";
}
s += " ' " + user + " '";
}
s += ")";
But it is more efficient to use a StringBuilder to assemble a String if there is looping involved.
StringBuilder sb = new StringBuilder("(");
boolean first = true;
for(String user : selUsers){
if (first) {
first = false;
} else {
sb.append(", ");
}
sb.append(" ' ").append(user).append(" '");
}
sb.append(")");
String s = sb.toString();

This does the trick.
String s = "";
for(String user : selUsers)
s += ", '" + user + "'";
if (selUsers.size() > 0)
s = s.substring(2);
s = "(" + s + ")";
But, a few pointers:
When concatenating strings like this, you are advised to work with StringBuilder and append.
If this is part of an SQL-query, you probably want to sanitize the user-names. See xkcd: Exploits of a Mom for an explanation.
For fun, a variation of Stephen C's answer:
StringBuilder sb = new StringBuilder("(");
boolean first = true;
for(String user : selUsers){
if (!first || (first = false))
sb.append(", ");
sb.append('\'').append(user).append('\'');
}
sb.append(')');
you could even do the loop it like this :-)
for(String user : selUsers)
sb.append(!first || (first=false) ? ", \'" : "\'").append(user).append('\'');

Use the 'old style' of loop where you have the index, then you add the comma on every username except the last:
String[] selUsers = {"a", "b", "c"};
String s="(";
for(int i = 0; i < selUsers.length; i++){
s+= " ' " + selUsers[i] + " ' ";
if(i < selUsers.length -1){
s +=" , ";
}
}
s+=")";
But as others already mentioned, use StringBuffer when concatenating strings:
String[] selUsers = {"a", "b", "c"};
StringBuffer s = new StringBuffer("(");
for(int i = 0; i < selUsers.length; i++){
s.append(" ' " + selUsers[i] + " ' ");
if(i < selUsers.length -1){
s.append(" , ");
}
}
s.append(")");

Use StringUtils.join from apache commons.

Prior to adding the trailing ')' I'd strip off the last character of the string if it's a comma, or perhaps just replace the trailing comma with a right parenthesis - in pseudo-code, something like
if s.last == ',' then
s = s.left(s.length() - 1);
end if;
s = s + ')';
or
if s.last == ',' then
s.last = ')';
else
s = s + ')';
end if;
Share and enjoy.

i would do s+= " ,'" + user + "'"; (place the comma before the value) and add a counter to the loop where i just do s = "'" + user + "'"; if the counter is 1 (or 0, depending on where you start to count).

(N.B. - I'm not a Java guy, so the syntax may be wrong here - apologies if it is).
If selUsers is an array, why not do:
selUsers.join(',');
This should do what you want.
EDIT:
Looks like I was wrong - I figured Java had this functionality built-in. Looks like the Apache project has something that does what I meant, though. Check out this SO answer: Java: function for arrays like PHP's join()?

I fully support Stephen C's answer - that's the one I wanted to suggest aswell: simply avoid adding the additional comma.
But in your special case, the following should work too:
s = s.replace(", \\)", ")");
It simply replaces the substring ", )" with a single bracket ")".

Java 1.4+
s = s.replaceFirst("\\, \\)$", ")");
Edited: I forgot last space before parethesis

StringBuilder has a perfectly good append(int) overload.
String [] array = {"1","2","3" ...};
StringBuilder builder = new StringBuilder();
builder.append(s + "( ")
for(String i : array)
{
if(builder.length() != 0)
builder.append(",");
builder.append(i);
}
builder.append(" )")
Answer shamelessly copied from here

Related

If statement with two conditions not working properly

I am new to programming and I am trying to create a program which parses a file and outputs the tokens. At the minute I am trying to create an if statement which will output the name of each operator with two characters, e.g. "&&" or "<=". My if statement does not work for "<=" as it picks up the '<" and '=' separately due to the earlier code:
else if (getOp(ch) != null) {
System.out.println(line + ", " + sglchar + ", "+ ch);
counter++;
continue;
}
My getOp(ch) method contains the operators with one character, however I cannot figure out how to do this with two character operators and my if statements don't seem to be doing the trick.
This is the if statement I am trying:
else if (prog.charAt(counter) == '<' && prog.charAt(counter+1) == '=') {
String str = "";
str += ch;
str += prog.charAt(counter++);
System.out.println(line + ", " + getOp(str) + ", " + str);
counter++;
continue;
}
As outlined in my comments, use of Java's Scanner class. It makes parsing text files very easy.
Consider the following:
Scanner sc = new Scanner(new File("file.txt"));
while (sc.hasNext()) {
String token = sc.next();
if (Pattern.matches("<=", token)) {
System.out.println(token);
}
}
sc.close();
}
outputs:
<=

String formatter function in java

I m writing a function to format a string input. The function is to make the text output left indented, with a limit to the number of characters in a line.
if there are excess whitespaces,' ', between words; i skip the excess whitespace and only put one whitespace' '. if the word is too long and will go over the character per line limit, i insert whitespaces until the limit and start a new line with that word in the newline.
i am unable to create the padding section of the code. which is the part which checks whether the word will go over the limit and to start a newline with the word in the newline.
as part of the assignment requirements, i am only allowed to use charAt() and length methods on a String
void runApp(){
String text = " Knowing You Jesus " +
" Graham Kendrick " +
"All I once held dear, built my life upon " +
"All this world reveres, and wars to own " +
"All I once thought gain I have counted loss " +
"Spent and worthless now, compared to this " +
"Knowing you, Jesus " +
"Knowing you, there is no greater thing " +
"You're my all, you're the best " +
"You're my joy, my righteousness " +
"And I love you, Lord " +
"Now my heart's desire is to know you more " +
"To be found in you and known as yours " +
"To possess by faith what I could not earn " +
"All-surpassing gift of righteousness " +
"Oh, to know the power of your risen life " +
"And to know You in Your sufferings " +
"To become like you in your death, my Lord " +
"So with you to live and never die " +
"Source: Musixmatch " +
"Songwriters: Tim Hughes / Ben Cantelon ";
//limit = 60
System.out.println(" `123456789012345678901234567890123456789012345678901234567890");`
System.out.println(leftTextFormat(text, 60));
System.out.println();
}
// This prints out everything left indented, but does not pad.
String leftTextFormat(String text, int limit){
String formattedText = "";
int charCount = 0;
formattedText = formattedText+"[";
for (int i=0; i<text.length(); i++){
if (charCount%limit ==0){
if (text.charAt(i) == ' '){
continue;
}else if (text.charAt(i) != ' ' ){
formattedText = formattedText+text.charAt(i);
charCount++;
}
}else if (charCount%limit != 0){
if (text.charAt(i) == ' '){
if (text.charAt(i-1) != ' '){
formattedText = formattedText+text.charAt(i);
charCount++;
}else{
continue;
}
}else if (text.charAt(i) != ' '){
formattedText = formattedText+text.charAt(i);
charCount++;
}
}
if (charCount%limit ==0 && charCount!=0){
formattedText = formattedText+"]\n[";
}
}
return formattedText;
}
The expected output is this:
https://drive.google.com/file/d/1uYXtSBo37sFnpwJeBGtjF0MFYNngtZXv/view?usp=sharing
what i managed to do is this:
https://drive.google.com/file/d/102zNMe4JhaO2IUoOPCS5GSZ02Pq9aXwX/view?usp=sharing
123456789012345678901234567890123456789012345678901234567890
[Knowing You Jesus Graham Kendrick All I once held dear, buil]
[t my life upon All this world reveres, and wars to own All I]
[once thought gain I have counted loss Spent and worthless no]
[w, compared to this Knowing you, Jesus Knowing you, there is]
[no greater thing You're my all, you're the best You're my jo]
[y, my righteousness And I love you, Lord Now my heart's desi]
[re is to know you more To be found in you and known as yours]
[To possess by faith what I could not earn All-surpassing gif]
[t of righteousness Oh, to know the power of your risen life ]
[And to know You in Your sufferings To become like you in you]
[r death, my Lord So with you to live and never die Source: M]
[usixmatch Songwriters: Tim Hughes / Ben Cantelon
Ok attempt, but your problem is that you only adding characters and never actually establishing if those characters make up words and if those words, which you are adding, are going to go over your "limit". Hence you have no idea when a word will actually cause you to go over your imposed limit and subsequently you are make no attempt to pad your line when you are potentially going to go over that limit.
Essentially you need to work word for word and line by line. Each time you've established a word, check that the length of that word plus the length of your current line is not greater than your limit. If it's greater don't concatenate it to your current line, rather pad the line to your limit and start a new line.
public String formattedLine(String singleLine, int limit) {
int padding = limit - singleLine.length();
String pad ="";
for(int j = 0; j < padding; j ++) {
pad += " ";
}
return "[" + singleLine + pad + "]\n";
}
public String leftTextFormat(String text, int limit) {
String word = "";
String singleLine = "";
String formattedText = "";
for(int i=0; i<text.length(); i++) {
if (text.charAt(i) != ' ') {
word = word + text.charAt(i);
} else {
if(word.length() > 0) {
if(singleLine.length() + word.length() >= limit) {
formattedText = formattedText + formattedLine(singleLine, limit);
singleLine = "";
}
if(singleLine.length() == 0) {
singleLine = word;
} else {
singleLine = singleLine + " " + word;
}
word = "";
}
}
}
formattedText = formattedText + formattedLine(singleLine, limit);
return formattedText;
}

Stop words not being correctly removed from string

I have a function which reads stop words from a file and saves it in a HashSet.
HashSet<String> hset = readFile();
This is my string
String words = "the plan crash is invisible";
I am trying to remove all the stop words from the string but it is not working correctly
The output i am getting: plan crash invible
Output i want => plan crash invisible
Code:
HashSet<String> hset = readFile();
String words = "the plan crash is invisible";
String s = words.toLowerCase();
String[] split = s.split(" ");
for(String str: split){
if (hset.contains(str)) {
s = s.replace(str, "");
} else {
}
}
System.out.println("\n" + "\n" + s);
While hset.contains(str) matches full words, s.replace(str, ""); can replace occurrences of the "stop" words which are part of words of the input String. Hence "invisible" becomes "invible".
Since you are iterating over all the words of s anyway, you can construct a String that contains all the words not contained in the Set:
StringBuilder sb = new StringBuilder();
for(String str: split){
if (!hset.contains(str)) {
if (sb.length() > 0) {
sb.append(' ');
}
sb.append(str);
}
}
System.out.println("\n" + "\n" + sb.toString());
No need so check if your string contain the stop word or split your string, you can use replaceAll which use regex, like this :
for (String str : hset) {
s = s.replaceAll("\\s" + str + "|" + str + "\\s", " ");
}
Excample :
HashSet<String> hset = new HashSet<>();
hset.add("is");
hset.add("the");
String words = "the plan crash is invisible";
String s = words.toLowerCase();
for (String str : hset) {
s = s.replaceAll("\\s" + str + "|" + str + "\\s", " ");
}
s = s.replaceAll("\\s+", " ").trim();//comment and idea of #davidxxx
System.out.println(s);
This can gives you :
plan crash invisible

Printing multiple strings from an array as a single string

I want to print multiple Strings from an Array utilizing a for-loop, it will print a full first and last name, but only once. Here's my method for doing this.
This is the output I get:
"firstName secondName, "
There should be mutliple full names being printed.
The problem here is that in each iteration, you create a new memory location for list and so every time the loop executes, the value of list is overwritten. You can fix this by appending to list instead of changing the value of list in every iteration.
A side note, since Strings are immutable in java, for every iteration of the for loop, new memory will be allocated for list. This is not very efficient. You should instead use StringBuilder which is mutable. It would look like this.
StringBuilder str = new StringBuilder(list);
Then you can append to str :
str.append("any string");
This is equivalent to str + "any string"
Using StringBuilder, memory will be allocated to str only once and all the changes will take in place which is much more efficient. And finally you want to return a String object so you can call the method toString() on the StringBuilder object to convert it back into a String.
So, finally it would look like this :
public String getTANames() {
StringBuilder str = new StringBuilder("");
for(int i = 0; i < TAList.length; i++){
str.append(TAList[i].first + " " + TAList[i].second + ", ");
}
return str.toString();
}
You are very close. The problem is you keep resetting list every time you iterate over TANames. Try this instead:
public String getTANames() {
String list = "";
for(int i = 0; i < TAList.length; i++){
list += TAList[i].first + " " + TAList[i].second + ", ";
}
return list;
}
The difference is this line here: list += TAList[i].first + " " + TAList[i].second + ", "; you are adding to list not setting list.
In your current code, every loop changes the value of the list variable. To fix the issue, replace the current = with the += as follows:
list += TAList[i].first + " " + TAList[i].second + ", ";
public String getTANames() {
String list = "";
for(int i = 0; i < TAList.length; i++){
list += TAList[i].first + " " + TAList[i].second + ", ";
}
return list;
}
Hope that helps.

Automating search functionality using Selenium - Java

I need to automate search functionality as below:
Search string = (X* OR "Y") AND Z
On entering this search system should assert the result. My problems are:
1) How to make precedence among operators because if there is () then that should be executed and with its result other parts of search string to be checked.
2) termi* can be terminate, terminator. How do we check this and assert
3) "Stack Overflow" means the result should have exactly matched. How can we find and assert
4) Likewise NOT operator, how can we assert
Pls share with me if any kind of help you can provide.
Thanks in advance.
Some how managed to write code in java using StringBuffer :)
Instead of storing the result of first block and process next I have created a string command based on the searchString as below and finally fire the newly created command and verified the answer.
Like whenevenever AND comes in searchString we insert && operator and for OR || operator.
String[] arrSearch=searchString.split("\\s");
StringBuffer sb = new StringBuffer();
boolean skipFlag = false;
for(int i=0;i<arrSearch.length;i++){
System.out.println(arrSearch[i]);
if(!skipFlag && arrSearch[i].startsWith("\"")){
skipFlag = true;
continue;
}else if(skipFlag){
if(arrSearch[i].endsWith("\"")){
skipFlag = false;
continue;
}else{
continue;
}
}else if(arrSearch[i].startsWith("(")){
String temp = arrSearch[i].substring(1);
sb.append("(selenium.isTextPresent(" + temp + ")" + " ");
}else if(arrSearch[i].startsWith(")")){
String temp = arrSearch[i].substring(0,arrSearch[i].length()-1);
sb.append("selenium.isTextPresent(" + temp + "))" + " ");
}else if(arrSearch[i].equalsIgnoreCase("AND")){
sb.append("&&" + " ");
}else if(arrSearch[i].equalsIgnoreCase("OR")){
sb.append("||" + " ");
}else if(arrSearch[i].equalsIgnoreCase("NOT")){
sb.append("!");
}else if(arrSearch[i].endsWith("*")){
String temp = arrSearch[i].substring(0,arrSearch[i].length()-1);
sb.append("selenium.isTextPresent(\"//*[contains('" + temp + "')]\")" + " ");
}else{
sb.append("selenium.isTextPresent(" + arrSearch[i] + ")" + " ");
}

Categories

Resources