廖雪峰Java2面向对象编程-6Java核心类-1字符串和编码

Java的字符串用String表示

1.String特点:

  • 可以直接使用"..."表示一个字符串,不必使用new String:String s1 = "hello world";
  • 内容不可变
        String s = "hello world";
        System.out.println(s.equals("hello world"));

2.判断是否相等equals

    `    String s = "hello world";
        s.equals("hello world");
        s.equalsIgnoreCase("Hello WORLD");//忽略大小写

3.是否包含一个子串

contains:是否包含一个字串,boolean类型
indexOf:返回子串在原字符中的第一个位置的索引,没有返回-1,int类型
lastIndexOf:返回子串在原字符中最后一个位置的索引,没有返回-1,int类型
startsWith:原字符串是否以子串开始,boolean类型
endsWith:原字符串是否以子串结尾,boolean类型

        String s = "hello world";
        System.out.println(s + "是否包含world:" + s.contains("world"));
        System.out.println(s + "中第一个o的位置:"+ s.indexOf("o"));
        System.out.println(s + "最后一个o的位置:" + s.lastIndexOf("o"));
        System.out.println(s+ "是以ll开头:" + s.startsWith("ll"));
        System.out.println(s+"是以ld结尾:" + s.endsWith("ol"));

4.trim()移除字符串中的空格

  • 移除首尾空白字符
  • 空格 \t \r \n
  • 注意:trim不改变字符串内容,而是返回新字符串
        String s = " \thello world\r\n";
        System.out.println(s.trim());
        System.out.println("a"+s+"a");

5.提取字串

        String s = "hello world";
        System.out.println("4:"+s.substring(4));
        System.out.println("4-8:"+s.substring(4,8));

6.大小写转换

toUpperCase()转换为大写,可以加地区
toLowerCase()转换为小写,可以加地区

        String s = "hello world";
        System.out.println(s.toUpperCase());
        System.out.println(s.toLowerCase());
        System.out.println(s.toLowerCase(Locale.CANADA));
        System.out.println(s.toUpperCase(Locale.CANADA));


关于java.util.locale见(易佰教程)[https://www.yiibai.com/java/util/java_util_locale.html]
顺便吐槽以下,台独无处不在

7.替换字串replace

replace有2个重载方法,分别替换1个字符和1串字符
replaceAll(String regex, String replacement) 正则表达式替换字串
replaceFirst(String regex, String replacement)

        String s = "hello world";
        System.out.println(s.replace("l","r"));
        System.out.println(s.replace("ll","er"));

8.分割字符串split

通过正则表达式分割字符串

        String s = "hello world";
        String[] ss = s.split("[e|o]");
        System.out.println(Arrays.toString(ss));

9.拼接字符串static String join()

        String[] arr = {"A","B","C"};
        String s = String.join("~~",arr);
        System.out.println(s);

10.String类和其他数据类型的转换

总结:
字符串是不可变对象
字符串操作不改变原字符串内容,而是返回新字符串
常用的字符串操作:提取子串、查找、替换、大小写转换等
字符串和byte[]互相转换时要注意编码,建议总是使用utf-8编码

猜你喜欢

转载自www.cnblogs.com/csj2018/p/10289915.html