码点与代码单元
Java字符串由char值序列组成。char数据类型是一个采用UTF-16编码表示Unicode码点的代码单元。大多数的常用Unicode字符使用一个代码单元就可以表示,而辅助字符需要一对代码单元表示。
length方法将返回采用UTF-16编码表示的给定字符串所需要的代码单元数量。例:
String greeting = “Hello”;
int n = greeting.length(); //is 5
要想得到实际的长度,即码点数量,可以调用:
int cpCount = greeting.codePointCount(0, greeting.length());
调用s.cahrAt(n)将返回位置n的代码单元,n介于0 ~ s.length()-1之间。例:
char first = greeting.charAt(0);//first is ‘H’
char last = greeting.charAt(4);//last is ‘0’
要想得到第i个码点,应该使用下列语句
int index = greeting.offsetByCodePoint(0,i);
int cp = greeting.codePointAt(index);
常用的一些String Api
boolean equals(Object other)
如果字符串与other相等,返回true。
boolean startsWith(Strign prefix)
boolean endsWith(String suffix)
如果字符串以suffix开头或结尾,则返回true。
int indexOf(String str)
int length()
返回字符串长度。
String replace(CharSequence oldString,CharSequence newString)
返回一个新字符串。这个字符串用newString代替原始字符串中所有的oldString。可以用String或StringBuilder对象作为CharSequence参数。
String toLowerCase()
String toUpperCase()
返回一个新字符串。这个字符串将原始字符串中的大写字母改为小写,或者将原始字符串中的所有小写字母改成了大写字母。
String trim()
返回一个新字符串。这个字符串将删除了原始字符串头部和尾部的空格。-