原思路: 像括号配对一样,如果遇见select 就入栈,如果遇见from就出栈,直到栈为空,取得此时的位置,进行字符串截取。
实现方法:遇见字符s并且连续后5个字符elect 就+1,遇见字符f并且连续3个字符为rom就-1,当计数器结果为0时,返回当前字符的位置,然后进行字符串截取即可:
/**** * 获取截取位置 * @param selectSQL * @return */ public static int getSubIndex(String selectSQL){ System.out.println(selectSQL.length()); int count = 0; for(int i=0;i<selectSQL.length();i++){ char c = selectSQL.charAt(i); if(c ==‘s‘){ if(selectSQL.charAt(i+1)==‘e‘&&selectSQL.charAt(i+2)==‘l‘&& selectSQL.charAt(i+3)==‘e‘&&selectSQL.charAt(i+4)==‘c‘&& selectSQL.charAt(i+5)==‘t‘){ count++; i=i+5; }else{ continue; } }else if(c ==‘f‘){ if(selectSQL.charAt(i+1)==‘r‘&&selectSQL.charAt(i+2)==‘o‘&& selectSQL.charAt(i+3)==‘m‘){ count--; i=i+3; System.out.println(count); if(count == 0){ System.out.println(i); return i+1; } }else{ continue; } }else { continue; } } return -1; }
/** * 进行字符串截取 * @param inSQL * @return */ public static String getOutSQL(String inSQL){ int index = getSubIndex(inSQL); if(index != -1){ String outSQL = "select count(-1) from " + inSQL.substring(index); return outSQL; }else{ System.out.println("not a corrent sql"); return "not a corrent sql"; } }
原文地址:http://blog.csdn.net/topwqp/article/details/24597271