String类常用方法的使用:
public static void main(String[] args) { String s = " Hello World"; System.out.println(s);// Hello World //去掉字符串前后空白字符 /* System.out.println(s.trim());//Hello World s = s.trim();*/ //统计字符穿长度 System.out.println(s.length());//13 //字符串是否为空字符串 System.out.println(s.isEmpty());//如果返回值为 true 则为空字符串 //转换成大写字母 System.out.println(s.toUpperCase()); //转换成小写字母 System.out.println(s.toLowerCase());//汉字不分大小写,原样输出 //转换成字符数组 char[] chars = s.toCharArray(); System.out.println(chars);//直接输出字符数组,效果跟字符串效果一样,其他类型的数组输出格式不一样 System.out.println(Arrays.toString(chars));//[H, e, l, l, o, , W, o, r, l, d] 输出每个元素 int a[] = {1,2,3,4,5}; System.out.println(a);//直接输出int类型的数组变量格式是:[I@4554617c System.out.println(Arrays.toString(a));//[1, 2, 3, 4, 5] //转换成字节数组 byte[] bytes = s.getBytes(); System.out.println(bytes);//直接输出int类型的数组变量格式是:[B@74a14482 System.out.println(Arrays.toString(bytes));//[32, 32, 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] //获取指定位置的字符 char c = s.charAt(5); System.out.println("指定位置字符"+c); //末尾拼接字符串 System.out.println(s.concat("你好"));// Hello World你好 //查找字符串中是否包含指定的字符串,包含返回true,不包含赶回false System.out.println(s.contains("Hello")); //查找字符串中是否包含指定的字符或字符串,如果包含返回第一次出现的位置,如果不包含则返回-1 System.out.println("字符串中,字符 o 第一次出现的位置:"+s.indexOf('o')); //查找字符串中是否包含指定的字符或字符串,如果包含返回最后一次出现的位置,如果不包含则返回-1 System.out.println(s.lastIndexOf('o')); //截取字符串, 指定范围截取,包含前不包含(位置) System.out.println(s.substring(0, 5)); //截取字符串, 从指定位置开始到结尾 System.out.println(s.substring(6)); //分割字符串成字符串数组 String[] strings = s.split(" "); System.out.println(strings);//直接输出String类型的数组变量格式是: System.out.println(Arrays.toString(strings)); //判断字符串是否以指定字符串开始 System.out.println(s.startsWith("Hello")); //判断字符串是否以指定字符串结束 System.out.println(s.endsWith("World")); //比较两个字符串大小,如果大,返回正整数,小返回负整数,相等返回0 System.out.println(s.compareTo("Hello"));//比较规则:把两个字符串中字符逐个一一比较,根据ascii码顺序比较 //判断两个字符串是否相等 System.out.println(s.equals("Hello")); //判断两个字符串是否相等,忽略大小写,相等则返回true,否则为false System.out.println(s.equalsIgnoreCase("hello")); //替换字符或者字符串 System.out.println(s.replace('o', '欧')); System.out.println(s.replaceAll("Hello", "你好")); }