java:获取字符串中第一个汉字和第一个汉字汉字标点符号的位置?

如题所述

public static void main(String[] args) {
  //用Unicode码实现
  String s = "12345689我飞电风扇[],";
  //找第一个汉字
  for (int index = 0;index<=s.length()-1;index++){
   //将字符串拆开成单个的字符
   String w=s.substring(index, index+1);
   if(w.compareTo("\u4e00")>0&&w.compareTo("\u9fa5")<0){// \u4e00-\u9fa5 中文汉字的范围
    System.out.println("第一个中文的索引位置:"+index+",值是:"+w);
    break;
   }
   }
  //找第一个中文符号
  for (int index = 0;index<=s.length()-1;index++){
   //将字符串拆开成单个的字符
   String w=s.substring(index, index+1);
   String reg ="【。,!?】";//存放你要检测的中文符号
   if(reg.indexOf(w)!=-1){//
    System.out.println("第一个中文符号的索引位置:"+index+",值为:"+w);
    break;
   }
   }

}

运行结果:

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-12-05
package tool;

public class CopyCat
{
public static void main ( String[] args )
{
String string = "adf你.?的说法sdf";
String reg = "[\u4e00-\u9fa5]";
int index = -1;
if (string.matches (".*" + reg + ".*"))
{
index = string.split (reg)[0].length ();
}
System.out.println (index);
String regex = "[。,!?()《》……、:——【】;’”‘“]";
int ind = -1;
if (string.matches (".*" + regex + ".*"))
{
ind = string.split (regex)[0].length ();
}
System.out.println (ind);
}
}

本回答被提问者和网友采纳
第2个回答  2014-12-05
根据字符串长度,直接用substring就可以了哇。
第3个回答  2014-12-05
string.getIndexOf('正则表达式?')??
第4个回答  2014-12-05
substring 楼主最好参考下java的api
相似回答