字符串及其常用方法

  • 字符串是常量,创建之后不能改变,给字符串赋值时并没有修改数据,而是重新开辟了一块空间
  • 字符串字面值存储在字符串池(方法区中)中,可以共享
  • String s = “Hello”; 产生一个对象,字符串池中存储
  • String s = new String(“Hello”); 产生两个对象,堆、池各存储一个

实例代码

package string;

public class StringTest {
    public static void main(String[] args) {
        String name = "hello";
        name = "张三";
        String name2 = "张三";
        
        //字符串的另一种创建方式
        String str = new String("java");
        String str2 = new String("java");
        System.out.println(str == str2);
    }
}

在这里插入图片描述

常用方法

  • 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 lastIndex(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做拆分
  • public String substring(range); //截取字符串
String content = "Java is the best programming language";
        System.out.println(content.replace("Java", "Php"));
        String say = "Java is the best programming language, java xiang";
        String[] arr = say.split("[ ,]");
        String[] arr2 = say.split("[ ,]+")//不小心多打了几个符号的处理方法
        System.out.println(arr.length);
        for(String string : arr){
            System.out.print(string + "---");
        }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值