日期:2014-05-20  浏览次数:20776 次

急:请教一个中文字符串匹配问题
Java code

InputStream is = getClass().getResourceAsStream("/BookMark/" + this.MARK_PATH);
        if (is != null) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            int ch = 0;
            try {
                while ((ch = is.read()) != -1) {
                    baos.write(ch);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            byte[] text = baos.toByteArray();
            try {
                baos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                str = new String(text, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
 
现在用UTF-8读取了.txt文件中的内容存在buffer中,现在用一个中文字符串与之匹配(此中文字符串是用FileConnection读取的文件夹下的文件名称)与buffer中匹配,只有名称为ascii码才能匹配(indexOf返回正确),否则如果是中文匹配就返回-1.
Java code

public int getBookMark(String name) {
        int st = 0;
        int ed = 0;
        String[] array = null;
        System.out.println(name);
        st = bookMarks.indexOf(name);
        if(st == -1)
            return -1;
        ed = bookMarks.indexOf(";", st);
        array = Config.split(bookMarks.substring(st, ed), "=");
        return Integer.parseInt(array[1]);
    }

请问如何正确转换字符串使之匹配。
  很是头疼,希望达人不吝赐教。

------解决方案--------------------
因为你从文件读入的字符串缓存在buffer中,字符串编码是utf-8,那么你在参数中传入的name中的字符串内容也要用utf-8编码才能得出正确的比较结果,否则肯定是不正确的。
------解决方案--------------------
have a try
name = new String(name.getBytes("UTF-8"), "UTF-8"); // add code here to have a try
st = bookMarks.indexOf(name);
if(st == -1)
return -1;
ed = bookMarks.indexOf(";", st);
array = Config.split(bookMarks.substring(st, ed), "=");

------解决方案--------------------
我不知道别人是怎么用的,一般为了系统的通用性,一般我们只能收到的数据进行转码,并不指定到底转成什么类型的字符,
如String st=new String("*********");
String s2=new String(st.getByte("utf-8")),这样他生成的数据是以操作系统的字符集来决定,因我一般我们生成的字符类型,查看好像正确,但是数据保存到数据库里又变成乱码了,如果以操作系统为标准的话,一般就不会出问题了。

当然如果你知道自己的应用环境的话,不会出现别的问题,指定字符类型的话,当然最好了。
------解决方案--------------------
呵呵

顶上去

那不也一样的
------解决方案--------------------
关注下