JAVA String方法中public int indexOf(int ch)问题

在JAVA中返回一个字符在字符串的位置首次出现的位置时候,String 给我们提供几个有效的API。

<span style="font-family:SimSun;font-size:18px;"> int indexOf(int ch) 
      //返回指定字符在此字符串中第一次出现处的索引。
 int indexOf(int ch, int fromIndex) 
      //返回在此字符串中第一次出现指定字符处的索引,从指定的索引开始搜索。
 int indexOf(String str) 
      //返回指定子字符串在此字符串中第一次出现处的索引。
 int indexOf(String str, int fromIndex) 
      //返回指定子字符串在此字符串中第一次出现处的索引,从指定的索引开始。</span>
举个例子:

<span style="font-family:SimSun;font-size:18px;">class Demo1
{
	public static void main(String[] args){
		System.out.println("hello world".indexOf('l'));
		//返回值为2
		System.out.println("hello world".indexOf('o',5));
		//返回值为7
	}
}</span><span style="font-family:SimSun;font-size:24px;">	</span>
我们总是很习以为常的取用这个函数,传入一个字符去寻找这个字符首次出现的位置,但是我们仔细的看下JDK的函数声明public int indexOf(int ch),请注意这里的函数的局部参数是数据类型是int,而不是我们认为是char,在JAVA中int类型定义为4个字节,而char类型定义为2个字节,虽然我们可以将char 自动转换为int,但是JDK为什么不直接声明为public int indexOf(char ch),这就是我们今天要讨论的问题。

  首先JAVA使用的Unicode编码长度是是4个字节,也就是说一个int大小为是可以容纳一个Unicode的编码的长度的。Unicode的编码中第一字节称为组,第二字节称为面,第三字节称为行,第四字节称为点。第0组第0面里的字符可以只用2个字节表示,且涵盖了绝大部分的常用字。为了方便称呼,Unicode给它了一个名称——基本多文种平面BMP  Basic Multilingual Plane)。基本多文种平面值域和上域都是0FFFF,共计65535个码点。并且ASCII中有的字符Unicode中都有,并且对应相同的编码数字,并不是我们简单的认为Unicode编码一个char就可以存下数据。

我们看下String的indexOf(int ch)的源代码:

<span style="font-family:SimSun;font-size:18px;">   public int indexOf(int ch, int fromIndex) {
        final int max = value.length;
        if (fromIndex < 0) {
            fromIndex = 0;
        } else if (fromIndex >= max) {
            // Note: fromIndex might be near -1>>>1.
            return -1;
        }

        if (ch < Character.MIN_SUPPLEMENTARY_CODE_POINT) {
            // handle most cases here (ch is a BMP code point or a
            // negative value (invalid code point))
            final char[] value = this.value;
            for (int i = fromIndex; i < max; i++) {
                if (value[i] == ch) {
                    return i;
                }
            }
            return -1;
        } else {
            return indexOfSupplementary(ch, fromIndex);
        }
    }</span>
@param   ch character (Unicode code point)  参数ch 是一个Unicode的代码点

什么是代码点?代码点 Code Point:与一个Unicode编码表中的某个字符对应的代码值。Java中用char来表示Unicode字符,由于刚开始Unicode最多使用16bit表示。因此char能够表示全部的Unicode字符。后来由于Unicode4.0规定Unicode支持的字符远远超过65536个字符。因此char现在不能表示所有的unicode字符。仅仅能表示0x000000到0x00FFFF(00 代表的就是拉丁文及其符号)之间的字符。也就是说,char不能表示增补字符。

Java中用int表示所有Unicode代码点。int的21个低位(最低有效位)用于表示Unicode代码点,并且11个高位(最高有效位)必须为零。也就是说,int能表示出char不能表示的增补字符。我们还可以看到,indexOf()有一个if{}else{}语句当超过Unicode的代码补充范围时候,就会调用indexOfSupplementartary()方法。他是处理超过范围的问题的。这里其实我们就可以记住indexOf(int ch)其实是传入的Unicode的代码点,不是传入的真正的字符,而且Java中的代码点是用32为数据表示的,因次是用int而不是char


  • 8
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
大多源码来自互联网,本人只做部分正和 import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import com.vince.*; /** * 将本地文件以哪种编码输出 * @param inputfile 输入文件的路径 * @param outfile 输出文件的路径 * @param code 输出文件的编码 * @throws IOException */ public class Charchange{ public static void main(String[] args) throws IOException { String inputfile,outputfile,code; inputfile = "D:\\迅雷\\work\\fen\\2-temp-test.txt";//要转码的文件 outputfile = "D:\\迅雷\\work\\1.txt";//输出的文件 code = "utf-8"; System.out.println("转码开始"); convert(inputfile,outputfile,code); System.out.println("转码完成"); } public static void convert(String inputfile,String outfile,String code) throws IOException { StringBuffer sb = new StringBuffer(); StringBuffer sb2 = new StringBuffer(); //得到当前文件的编码 String ch=getCharset(inputfile); InputStreamReader isr=null; OutputStreamWriter osw =null; //根据当前文件编码进行解码 if(ch.equals("UTF8")){ isr= new InputStreamReader(new FileInputStream(inputfile), "UTF-8"); }else if(ch.equals("Unicode")){ isr= new InputStreamReader(new FileInputStream(inputfile), "Unicode"); }else { isr= new InputStreamReader(new FileInputStream(inputfile), "GB2312"); } //将字符串存入StringBuffer BufferedReader br = new BufferedReader(isr); String line = null; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); isr.close(); //以哪种方式写入文件 if("UTF-8".equals(code)){ osw = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"); }else if("GB2312".equals(code)){ osw = new OutputStreamWriter(new FileOutputStream(outfile), "GB2312"); }else if("Unicode".equals(code)){ osw = new OutputStreamWriter(new FileOutputStream(outfile), "Unicode"); }else{ osw = new OutputStreamWriter(new FileOutputStream(outfile), "UTF-8"); } BufferedWriter bw = new BufferedWriter(osw); String sb1 = sb.toString(); String a1 = deal(sb1); bw.write(a1); bw.close(); osw.close(); } /** * 根据文件路径判断编码 * @param str * @return * @throws IOException */ private static String getCharset(String str) throws IOException{ BytesEncodingDetect s = new BytesEncodingDetect(); String code = BytesEncodingDetect.javaname[s.detectEncoding(new File(str))]; return code; } //本方法完成单个无字符的转换 public static String Change(String temp){ String myString = temp.replace("&#", ""); String[] split = myString.split(";"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < split.length; i++) { sb.append((char)Integer.parseInt(split[i])); } return sb.toString(); } //接收String sb1并对字符串的联合处理 public static String deal(String sb1) { //模块化开始 String car="";//小车运输单个字符 while(sb1.length()!=0){ int markStar = sb1.indexOf("&"); //判断方法是以&开头的数据默认为要处理的无字符 if(markStar==0){ String temp = sb1.substring(markStar,8); car = car+Change(temp); sb1=sb1.substring(8); }else if(markStar==-1&sb1;.length()>0){ String temp = sb1.substring(0,sb1.length()); car = car+temp; sb1=sb1.substring(sb1.length()); }else{ String temp = sb1.substring(0,markStar); car = car+temp; sb1=sb1.substring(markStar); } } return car.toString() ; } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值