day28--String类

JAVA 常用类

String类

String概述

  • 字符串是常量,创建之后不可改变。

  • 字符串字面值存储在字符串池中,可以共享。

  • String s="Hello";产生一个对象,字符串池中存储。

  • String s=new String("Hello");产生两个对象,堆、池各存储一个。


常用方法

  • public int length():返回字符串的长度;

  • public char charAt(int index):根据下标获取字符;

  • public boolean contains(String str):判断当前字符串中是否包含str;

  • public char[] toCharArray():将字符串转换成数组;

  • public int indexOf(String str):查找str首次出现的下标,存在,则返回该下标;不存在,则返回-1;

  • public int lastIndexOf(String str):查找字符串在当前字符串中最后一次出现的下标索引;

  • public String trim():去掉字符串前后的空格;

  • public String toUpperCase():将小写转大写;

  • public boolean endWith(String str):判断字符串是否以str结尾

  • public String replace(char oldChar,char newChar):将旧字符串替换成新字符串;

  • public String[] split (String str):根据str做拆分。


案例演示

  • 需求

    • 已知String str=“this is a text";

      1. 将str中的单词单独获取出来

      2. 将str中的text替换成practice

      3. 在text前面插入一个easy

      4. 将每个单词的首字母改为大写

 

可变字符串

  • StringBuffer:可变长字符串,JDK1.0提供。运行效率慢,线程安全。

  • StringBuilder:可变长字符串,JDK5.0提供。运行效率快,线程不安全。

  • 和String的区别:

    1. 效率比String高;

    2. 比String节省内存。

 

 

posted @ 2021-04-21 16:52  dddddmm  阅读(50)  评论(0)    收藏  举报