I have a SQL query passed to me in a text, here is a part of it:
WHERE
(t.STIME > CAST(SYSTIMESTAMP AS TIMESTAMP) + NUMTODSINTERVAL(-86400000 * 0.001, 'SECOND'))
) t ORDER BY
m_2 ASC, m_1 ASC, t.STIME ASC
What I want to do, is to simply modify it in a way that I will have:
WHERE
(t.STIME > CAST(SYSTIMESTAMP AS TIMESTAMP) + NUMTODSINTERVAL(-86400000 * 0.001, 'SECOND'))
ORDER BY
m_2 ASC, m_1 ASC, t.STIME ASC )
So, I need to somehow remove: ") t" from within the String, but how to do that? I always receive "unmatched ')' parenthesis and I really don't know why x/
Here is a method I wrote for replacing this string:
public static String replaceLast(String string, String toReplace, String replaceWith) {
int last = string.lastIndexOf(toReplace);
if (last < 0) return string;
String ending = string.substring(last).replaceFirst(toReplace, replaceWith);
return string.substring(0, last) + tail;
}
then I'm trying to use it this way:
if(sqlToTrim.lastIndexOf("\\) t") > 0){
replaceLast(sqlToTrim, "\\) t ", " ");
addLastParanthesis(sqlToTrim);
}
But it is not replaced, basicly nothing changes - replaceLast is never used. I assume I messed up with regex, I searched through stack overflow but it seems \ is the right combination that I should put before ). Thanks in advance for your help. Could anyone tell me what am I doing wrong?
If you need to know, why do I do that, why in this way - legacy code...
Strings are immutable. replaceLast(sqlToTrim, "\\) t ", " "); returns a new string. Do:
sqlToTrim = replaceLast(sqlToTrim, "\\) t ", " ");
and continue on from there. If addLastParenthesis modifies the string it should return it, i.e.
sqlToTrim = replaceLast(sqlToTrim, "\\) t ", " ");
sqlToTrim = addLastparenthesis(sqlToTrim);
Related
I'm working on an exercise for learning Java where I am supposed to write a method to print to the screen all items that come after the word "category:". This is my attempt at it:
public static void main(String[] args) {
String str = "We have a large inventory of things in our warehouse falling in "
+ "the category:apperal and the slightly "
+ "more in demand category:makeup along with the category:furniture and _.";
printCategories(str);
}
public static void printCategories(String passedString) {
int startOfSubstring = passedString.indexOf(":") + 1;
int endOfSubstring = passedString.indexOf(" ", startOfSubstring);
String categories = passedString.substring(startOfSubstring,endOfSubstring);
while(startOfSubstring > 0) {
System.out.println(categories);
startOfSubstring = passedString.indexOf((":") + 1, passedString.indexOf(categories));
System.out.println(startOfSubstring);
System.out.println(categories);
}
}
So the program should print:
apperal
makeup
furniture
My attempt is that the program should print the substring where it finds the starting index as ":" and the ending index as " ". Then it does the same thing again, only except from starting the very beginning of the variable str, this time it starts from the beginning of the last category found.
Once there are no more ":" to be found, the indexOf (part of startOfSubstring) will return -1 and the loop will terminate. However, after printing the first category it keeps returning -1 and terminating before finding the next category.
The two lines:
System.out.println(startOfSubstring);
System.out.println(categories);
Confirm that it is returning -1 after printing the first category, and the last line confirms that the categories variable is still defined as "apperal". If I comment out the line:
startOfSubstring = passedString.indexOf((":") + 1, passedString.indexOf(categories));
It returns the startOfSubstring as 77. So it is something to do with that line and attempting to change the start of search position in the indexOf method that is causing it to return -1 prematurely, but I cannot figure out why this is happening. I've spent the last few hours trying to figure it out...
Please help :(
There are a couple of issues with the program:
You're searching passedString for (":") + 1 which is the string ":1", probably not what you want.
You should evaluate endOfSubstring and categories inside the loop.
This is probably close to what you want:
public static void printCategories(String passedString) {
int startOfSubstring = passedString.indexOf(":") + 1;
while(startOfSubstring > 0) {
int endOfSubstring = passedString.indexOf(" ", startOfSubstring);
// If "category:whatever" can appear at the end of the string
// without a space, adjust endOfSubstring here.
String categories = passedString.substring(startOfSubstring, endOfSubstring);
// Do something with categories here, maybe print it?
// Find next ":" starting with end of category string.
startOfSubstring = passedString.indexOf(":", endOfSubstring) + 1;
}
}
I have corrected (in a comment) where you set the new value of startOfSubstring
while(startOfSubstring > 0) { // better if you do startOfSubstring != -1 IMO
System.out.println(categories);
// this should be startOfSubstring = passedString.indexOf(":", startOfSubstring +1);
startOfSubstring = passedString.indexOf((":") + 1, passedString.indexOf(categories));
System.out.println(startOfSubstring);
System.out.println(categories);
}
I'm building a small app which auto translates boolean queries in Java.
This is the code to find if the query string contains a certain word and if so, it replaces it with the translated value.
int howmanytimes = originalValues.size();
for (int y = 0; y < howmanytimes; y++) {
String originalWord = originalValues.get(y);
System.out.println("original Word = " + originalWord);
if (toReplace.contains(" " + originalWord.toLowerCase() + " ")
|| toCheck.contains('"' + originalWord.toLowerCase() + '"')) {
toReplace = toReplace.replace(originalWord, translatedValues.get(y).toLowerCase());
System.out.println("replaced " + originalWord + " with " + translatedValues.get(y).toLowerCase());
}
System.out.println("to Replace inside loop " + toReplace);
}
The problem is when a query has, for example, '(mykeyword OR "blue mykeyword")' and the translated values are different, for example, mykeyword translates to elpalavra and "blue mykeyword" translates to "elpalavra azul". What happens in this case is that the result string will be '(elpalavra OR "blue elpalavra")' when it should be '(elpalavra OR "elpalavra azul")' . I understand that in the first loop it replaces all keywords and in the second it no longer contains the original value it should for translation.
How can I fix this?
Thank you
you can sort originalValues by size desc. And after that loop through them.
This way you first replace "blue mykeyword" and only after you replace "mykeyword"
The "toCheck" variable is not explained what is for, and in any case the way it is used looks weird (to me at least).
Keeping that aside, one way to answer your request could be this (based only on the requirements you specified):
sort your originalValues, so that the ones with more words are first. The ones that have same number of words, should be ordered from more length to less.
I have requirement that need to get all combinations of given Strings.
For example
I have a String of digits and some special charcters
String chars="0123456789##$%&";
String guessedPw="authentic";
So I want to get combinations like this
$authentic%4
authentic##
5&authentic
authentic8
How should I improve my method to get all combinations?
This is the code that I have written.
but it doesn't give me all combinations.
private static String combination(String prefix, String s, String pw, String md5Pw) {
String pwFound = "";
if (s.length() > 0) {
// System.out.println(prefix + s.charAt(0) + pw);
String tempPw1 = prefix + s.charAt(0) + pw;
System.out.println("pw1 : " + tempPw1);
if (md5(tempPw1).equals(md5Pw)) {
// String tempPw1;
pwFound = tempPw1;
return pwFound;
}
String tempPw2 = pw + prefix + s.charAt(0);
if (md5(tempPw2).equals(md5Pw)) {
// String tempPw1;
pwFound = tempPw2;
return pwFound;
}
pwFound = combination(prefix + s.charAt(0), s.substring(1), pw, md5Pw);
pwFound = combination(prefix, s.substring(1), pw, md5Pw);
}
return pwFound;
}
Just if you don't want write own algo, you can use google.
Try to search for: "Generate Permutations".
For example, on this link: Generate all combinations from multiple lists there is a algo which you can use it (but with list).
void GeneratePermutations(List<List<Character>> Lists, List<String> result, int depth, String current)
{
if(depth == Lists.size())
{
result.add(current);
return;
}
for(int i = 0; i < Lists.get(depth).size(); ++i)
{
GeneratePermutations(Lists, result, depth + 1, current + Lists.get(depth).get(i));
}
}
But sure, there are a lot of other ways.
If you want to code everything by your own then this is how you should approach your problem =>
Have a special character say ~ to denote guessedPw, and create another string say str = chars + "~".
Now first you need to look for all possible combinations of str, finding which will take exponential time , and then for each found combination, you should generate all it's permutation , which is again factorial time complex. And then in the final string , you should replace all the occurrence of '~' with guessedPw, and get the answer string.
Here you go for the link for generating permutations and combinations :
Link : http://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/
To find out combinations , you can use bit-masking if you have at max. 64 characters in the string , combinations from which you want to extract.
To make new combination, you can add one char as prefix or add one char as suffix. To avoid repeats, stop adding prefix when suffix exists
Pseudocode:
GenPass(CurrentString, boolAllowPrefix)
check CurrentString, return it if good result
check length limit, exit if too long
for c in Chars
if (boolAllowPrefix)
GenPass(Chars[i] + CurrentString, True)
GenPass(s + Chars[i], False)
Delphi implementation to check
procedure GenPass(s: string; bPrefix: Boolean);
var
i: integer;
begin
List.Add(s);
if Length(s) = MaxLen then
Exit;
if bPrefix then
for i := 1 to Length(Chars) do
GenPass(Chars[i] + s, True);
for i := 1 to Length(Chars) do
GenPass(s + Chars[i], False);
end;
I'm trying to debug a problem I've on a script, I'm newly to Java I think it's a simplest thing but I need to understand. This :
for( Map.Entry<String,int[]> entry : this.indexMap.entrySet())
{
if( !entry.getKey().equals("nickname"))
{
System.out.print("'"+ entry.getKey() +"' contains "+ entry.getKey().length() +" chars");
System.out.print("'"+ name +"' contains "+ name.length() +" chars");
}
else if( entry.getKey().trim().equals("nickname") )
{
System.out.print("Yes are sames");
}
}
For a String name = "nickname", displays me that :
18:56:15 [INFOS] 'nickname' contains 94 chars
18:56:15 [INFOS] 'nickname' contains 8 chars
I'm trying to understand this.
The problem is entry.getKey() returns the same thing as my string name, but not really the same. In first test, we saw the two vars are different, so the print is did, but the twos vars have the same value, and not the same length. In the else-if, I tried to remove spaces but not printed so where are from these 94 chars?
https://code.google.com/p/imdbparsers/source/browse/trunk/imdb+parsers/src/imdb/parsers/xmltosql/NamedParameterStatement.java?r=6
Is the code, methods concerned are
private String parse(String query)
private int[] getIndexes(String name)
line 161 et 89
This for loop i've in mine is only to debug the
int[] indexes = (int[]) indexMap.get(name);
Returns always null
The query string is :
SELECT COUNT(`account_id`) AS `total` FROM `game_accounts` WHERE `nickname`=:nickname
The difference between
entry.getKey().equals("nickname")
and
entry.getKey().trim().equals("nickname")
is trim().
The first take in account the spaces and the second not.
It's because they are a loop on a map: to find the 'bad' keys...
I think that if you reverse your if clauses you might get something that behaves more like what you are expecting, although it is somewhat unclear what you are asking. Comparing keys as the first clause in the if block makes the code simpler.
if( entry.getKey().trim().equals("nickname") )
{
System.out.print("Yes are sames");
}
else
{
System.out.print("'"+ entry.getKey() +"' contains "+ entry.getKey().length() +" chars");
System.out.print("'"+ name +"' contains "+ name.length() +" chars");
}
What arguments can You give for the use one or another variant that is better, faster, more correct.
First variant:
StringBuffer sql = new StringBuffer("SELECT DISTINCT f.ID ")
.append("FROM FIRST_TABLE F ")
.append("LEFT JOIN SECOND_TABLE s ON f.ID = s.F_ID ")
.append("WHERE ")
.append("F.BOOL = 1 ")
.append("AND S.DATE IS NOT NULL ")
.append("AND S.CLOSED = 0 ");
Second variant:
String sql = "SELECT DISTINCT f.ID " +
"FROM FIRST_TABLE F " +
"LEFT JOIN SECOND_TABLE s ON f.ID = s.F_ID " +
"WHERE "
"F.BOOL = 1 " +
"AND S.DATE IS NOT NULL " +
"AND S.CLOSED = 0";
*for note: Class String and Class StringBuffer.
The second is better:
It's clearer (more of the code has to do with what you want)
It's more efficient, as all the concatenation is being done at compile-time
Even if execution-time concatenation was required (e.g. you had a variable in there), the compiled code would use a StringBuilder or StringBuffer where it needed to (depending on the version of Java you're targeting).
Mind you, if you're executing a database query, the efficiency is going to be utterly insignificant.
You should not be wasting your time worrying about how to concatenate a few strings. Use 2 and keep it clear. Using StringBuilder/buffer is not the mark of a great programmer, if that's what you thought.
Worry about the vaguely defined requirements and the things behind schedule.
Try this ->
long finalTime1 = 0; {
long initialTimeTest = System.currentTimeMillis();
for( int index = 0; index < 10000; index++ ){ StringBuilder sb = new StringBuilder("Hello, ").append("World"); System.out.println(sb.toString()); }
finalTime1 = System.currentTimeMillis() - initialTimeTest;
}
long finalTime2 = 0; {
long initialTimeTest = System.currentTimeMillis();
for( int index = 0; index < 10000; index++ ){ String sb = "Hello, " + "World"; System.out.println( sb ); }
finalTime2 = System.currentTimeMillis() - initialTimeTest;
}
System.out.println( finalTime1 ); System.out.println( finalTime2 );
Results:
... Hello, World Hello, World 245 148
Did you think string buffer was faster ??
You are breaking the mother of all rules: Keep it Simple. -
For mundane string handling there is no reason why to use StringBuilder. It just adds unnecessary complexity to a mundane task.
We need to think BIG, think in the overall business impact of the module to the project. Discussing whether we shall assemble a few strings with StringBuilder/Builder or String is thinking little, - don't do that.
To your question about performance, I recommend:http://cfd.gmu.edu/~jcebral/academics/csi702/notes/02-optimization.pdf