关于解析字符串的:
如何把下面的语句
select * from table where str = 'aa ss '
分割成
select,*,from,table,where,str,=,'aa ss '其实就是基于空格来分割字符串,但是不能包括' '里面的空格,并且把连续的空格看作一个空格来处理
如何把下面的语句
select * from table where str = 'aa ss '
分割成
select,*,from,table,where,str,=,'aa ss '其实就是基于空格来分割字符串,但是不能包括' '里面的空格,并且把连续的空格看作一个空格来处理
String s1 = ss.substring(0,ss.indexOf("'"));
s1 = s1.replaceAll(" +",",");
System.out.println(s1+ss.substring(ss.indexOf("'")).trim());
public static void main(String[] args) {
String oldString = new String("select * from table where str = 'aa ss '");
char[] temp = new char[oldString.length()];
boolean judge = false;
int i=0;
int j=0;
int count=0;
for(i=0;i<oldString.length();i++)
{
if(oldString.charAt(i)=='\'')
{
count++;
if(count%2==1)
judge=true;
else
judge=false;
}
if(oldString.charAt(i)!=' ')
{
temp[j] = oldString.charAt(i);
j++;
}
else
{
if(judge)
{
temp[j] = oldString.charAt(i);
j++;
}
else
{
while(oldString.charAt(i+1)==' ')
i++;
temp[j] = ',';
j++;
}
}
}
String newString = new String(temp);
System.out.println(newString);
}
}
功能是能实现,就是方法好像有点笨,呵呵,只能想到这么多了
这个题目如果用正则来表达很简单。
SQL语句中=左右不一定有空格的。而且where的条件语句可能不止一条,用楼上的办法的话,分情况讨论很麻烦。用正则表达式就能一劳永逸。import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class TestRegular
{
public static void main(String[] args)
{
Pattern p=Pattern.compile("('[^']+')|([^\\s'=]+)|=");
Matcher m=p.matcher("select * from a where z = 'dd d' and air='ox'");
int i=0;
while (m.find())
{
System.out.println(m.group());
i++;
}
}
}