jvm - 关于Core Java 实例代码的问题?这两个到底有什么区别?

查看:117
本文介绍了jvm - 关于Core Java 实例代码的问题?这两个到底有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

package com.demo.string;

public final class StringDemo {
    public static void main(String[] args) {
        //测试的字符串
        String teststr = "hello";
        
        //length方法将返回采用utf-16编码表示的给定字符串所需要的代码单元数量
        int l = teststr.length();
        System.out.println(l);
        
        //要返回实际的长度,即代码点数量
        int cpCount = teststr.codePointCount(0, teststr.length());
        
    }
}

解决方案

Java的String类的内部其实维护的是一个char数组,查看[jdkdoc](https://docs.oracle.com/javase/7/docs/api/java/lang/String.html)可知:
length()方法即返回返回这个数组里面char的个数。Returns the length of this string.
public int codePointCount(int beginIndex, int endIndex)

Returns the number of Unicode code points in the specified text range of this String. The text range begins at the specified beginIndex and extends to the char at index endIndex - 1. Thus the length (in chars) of the text range is endIndex-beginIndex. Unpaired surrogates within the text range count as one code point each.

即返回这个string类中起始到终止位置的字符串。

这篇关于jvm - 关于Core Java 实例代码的问题?这两个到底有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆