Java中String类方法以及其实例

来源:互联网 发布:win10仿mac软件 编辑:程序博客网 时间:2024/06/03 23:41
package string;public class StringTest {public static void main(String[] args) {/** * String方法汇总:String str="Hello World!" * 1、charAt(int index)返回指定索引处的字符值 * 2、codePointAt(int index)返回指定索引处的字符ascll码值 * 3、codePointBefore(int index)返回指定字符前一个字符的ascll码值 * 4、compareTo(String anotherString)返回值为当前字符串首字母与目标字符串首字母ascll码值得差(考虑大小写) * (1)如果第一个字母相同,则比较第二个,以此类推 * (2)如果字符串前几个字符完全相同,则返回值为两个字符串长度的差 * (2)如果两个字符串完全相同,则返回值为0 * 5、compareToIgnoreCase(String antherString)用法同4,但是不区分大小写 * 6、concat(String str)连接字符串 * 7、contains(CharSequence s)返回值为true或false,该字符串是否含有指定序列的字符 * 8、contentEquals(CharSequence s)返回值为boolean,表示当前字符串与目标字符串是否相同 * 9、copyValueOf(char[] ,int ,int )静态方法,将字符数组转化为字符串,不写后两个参数表示全部复制,第一个参数表示开始复制的下标,第二个表示复制几个字符 * 10、endsWith(String)返回值为boolean,表示该字符串是否以指定的字符串结尾(区分大小写) * 11、equals()和equalsIgnoreCase()返回值为boolean,字符串是否相等,前者区分大小写,后者不区分大小写 * 12、getBytes()将字符串转化为Bytes数组 * 13、hashCode()返回字符串的哈希码 * 14、indexOf()返回值为指定字符第一次出现的下标,第二个参数表示起始位置,如果不写,则从头开始。如果不存在该函数返回-1 * 15、isEmpty()判断字符串是否为空,返回类型为boolean * 16、matches()判断目标字符串是否符合正则表达式,返回类型为boolean * 17、replace()将字符串中的指定字符替换为指定字符,默认全部替换 * 18、replaceAll()则用于正则表达式 * 19、split()根据正则表达式拆分目标字符串,返回值为String【】数组类型 * 20、starsWith()测试目标字符串是否以指定字符串开始 * 21、subSequence()根据起始下标截取字符串,包含头部不包含尾部 * 22、subString()根据起始下标截取字符串 * 23、toCharray()返回一个字符数组 * 24、toLowerCase()字符串转小写 * 25、toUpperCase()字符串转大写 */String str="Hello World!";char[] arr={'H','e','l','l','o',' ','W','o','r','l','d','!'};System.out.println("1、"+str.charAt(4));System.out.println("2、"+str.codePointAt(1));System.out.println("3、"+str.codePointBefore(1));System.out.println("4、"+str.compareTo("HHDSAF"));System.out.println("5、"+str.compareToIgnoreCase("ello World!"));System.out.println("6、"+str.concat("ello World!"));System.out.println("7、"+str.contains("ell"));System.out.println("8 、"+str.contentEquals("Hello World"));System.out.println("9、"+String.copyValueOf(arr,2,2));System.out.println("10、"+str.endsWith("D!"));System.out.println("11、"+str.equals("hello world!")+":"+str.equalsIgnoreCase("hello world!"));System.out.println("12、"+str.getBytes());System.out.println("13、"+str.hashCode());System.out.println("14、"+str.indexOf('l',4));System.out.println("15、"+str.isEmpty());System.out.println("16、"+str.matches("[a-zA-Z]+"));System.out.println("17、"+str.replace('l', '*'));System.out.println("18、"+str.replaceAll("[Wor]", "*"));System.out.println("19、"+str.split(" "));System.out.println("20、"+str.startsWith("h"));System.out.println("21、"+str.subSequence(1, 3));System.out.println("22、"+str.substring(1,4));System.out.println("23、"+str.toCharArray());System.out.println("24、"+str.toLowerCase());System.out.println("25、"+str.toUpperCase());}}
运行结果: