常用类库----String----常用操作

常用类库------String

1. String类概述

概述

java.lang.String类代表字符串。Java程序中所有的字符串文字都可以看成是实现此类的实例。

String中包括用于检查各个字符串的方法,比如用于比较字符串,搜索字符串,提取字符串以及创建具有翻译为大写小写的所有字符的字符串的副本。

特点

  1. 字符串不变:字符串的值在创建后不能被改变。
String s1 = "abc"; 
s1 += "d"; 
System.out.println(s1); // "abcd" 
// 内存中有"abc","abcd"两个对象,s1从指向"abc",改变指向,指向了"abcd"。	
  1. 因为String对象是不可变的,所以它们可以被共享。
String s1 = "abc"; 
String s2 = "abc"; 
// 内存中只有一个"abc"对象被创建,同时被s1和s2共享。
  1. "abc"等效于char[] data = {'a','b','c'}
String str = "abc"; 

相当于: 
char data[] = {'a', 'b', 'c'}; 
String str = new String(data); 
// String底层是靠字符数组实现的。

2. 使用步骤

  • 查看类
    • java.lang.String:此类不需要导入。
  • 查看构造方法
    • public String():初始化新创建的String对象,以使其表示空字符序列。
    • public String(char[] value):通过当前参数中的字符数组来构造新的String。
    • public Sting(byte[] bytes):通过使用平台的默认字符集解码当前参数中的字节数组来构造新的String。
    • 构造举例,代码如下
// 无参构造 
String str = new String(); 
    
// 通过字符数组构造 
char chars[] = {'a', 'b', 'c'}; 
String str2 = new String(chars); 

// 通过字节数组构造 
byte bytes[] = { 97, 98, 99 }; 
String str3 = new String(bytes);

3. 常用方法

判断功能的方法

  • public boolean equals(Object anObject):将此字符串与指定对象进行比较。
  • public boolean equalsIgnoreCase(String anotherString):将此字符串与指定对象进行比较,忽略大小写。
    • 方法演示,代码如下:
public class StringDemo01 {
    public static void main(String[] args) {
        //创建字符串对象
        String s1 = "hello";
        String s2 = "hello";
        String s3 = "Hello";

        //boolean equals(Object obj):比较字符串的内容是否相同
        System.out.println(s1.equals(s2));//true
        System.out.println(s1.equals(s3));//false
        System.out.println("------------------------------");

        //boolean equalsIgnoreCase(String stc):比较字符串的内容是否相同,忽略大小写
        System.out.println(s1.equalsIgnoreCase(s2));//true
        System.out.println(s1.equalsIgnoreCase(s3));//true
        System.out.println("*******************************");
    }
}

获取功能的方法

  • public int length():返回此字符串的长度。
  • pbulc String concat(String str):将指定的字符串连接到该字符串内的末尾。
  • public char charAt(int index):返回指定索引处的char值。
  • public int indexOf(String str):返回指定字符串第一次出现在该字符串内的索引。
  • public String substring(int beginIndex):返回一个子字符串,从beginIndex开始截取字符串到字符串结尾。
  • public String substring(int beginIndex,int endIndex):返回一个子字符串,从beginIndex到endIndex截取字符串,含beginIndex,不含endIndex。
    • 方法演示,代码如下:
public class StringDemo02 {
    public static void main(String[] args) {
        //创建字符串对象
        String s = "helloworld";

        //int length() 获取字符串的长度,也就是字符个数
        System.out.println(s.length());
        System.out.println("*******************************");

//        String concat(String str):将指定的字符串连接到该字符串的末尾
        String s1 = "java";

        System.out.println(s.concat(s1));
        System.out.println("*******************************");

        //`public char charAt(int index)`:返回指定索引处的char值。
//       :获取指定索引处的字符
        System.out.println(s1.charAt(1));//a
        System.out.println(s1.charAt(2));//v
        System.out.println(s1.charAt(3));//a
        System.out.println("*******************************");

//      public int indexOf(String str)`:返回指定字符串第一次出现在该字符串内的索引,没有返回-1
        System.out.println(s.indexOf("w"));//5
        System.out.println(s.indexOf("d"));//9
        System.out.println(s.indexOf("h"));//0
        System.out.println("*******************************");

//      String substring(int start): 从start开始截取字符串到字符串结尾
        System.out.println(s.substring(4));//oworld
        System.out.println(s.substring(5));//world
        System.out.println(s.substring(6));//orld
        System.out.println("*******************************");

//      String substring(int start,int end):从start到end截取字符串,含start,不含end
        System.out.println(s.substring(0,s.length()));//helloworld
        System.out.println(s.substring(3,8));//lowor
    }
}

转换功能的方法

  • public char[] toCharArray():将此字符串转换为新的字符数组。
  • public byte[] getBytes():使用平台的默认字符集将该String编码转换为新的字节数组。
  • public String replace(CharSequence target,CharSequence replacement):将与target匹配的字符串使用replacement字符串替换。
    • 方法演示代码如下:
public class StringDemo03 {
    public static void main(String[] args) {
        //创建字符串对象
        String s = "abcde";

        // char[] toCharArray():把字符串转换为字符数组
        char[] chs = s.toCharArray();
        for (char ch:chs) {
            System.out.println(ch);
        }
        System.out.println("-------------------------");

        //byte[] getBytes ():把字符串转换为字节数组
        byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
        for (byte by:bytes) {
            System.out.println(by);
        }
        System.out.println("-----------------------------");
        //替换字母it为IT
        String str = "itcast it it ";
        String replace = str.replace("it","IT");
        System.out.println(replace);//ITcast IT IT
    }
}
  • CharSequence 是一个接口,也是一种引用类型。作为参数类型,可以把String对象传递到方法中。

分割功能的方法

  • public String[] split(String regex):将此字符串按照给定的regex(规则)拆分为字符串数组。

方法演示,代码如下:

String s1 = "aa bb cc";
String[] strArray = s1.split(" ");
System.out.println(strArray.length);//3
for (String str:strArray) {
   	System.out.println(str);//aa bb cc
}

例题

  1. 编写一个方法,将一段文本中的各个单词的字母顺序翻转,例如:“I like writing code best”,将变成"I ekil gnitirw edoc tseb"。
    • 思路:用空格分开各个单词,将其放入char数组后翻转
public static void alphabeticalReversal(String a){
        String s = "";
        String[] text1 = a.split(" ");//将此字符串拆分
        for (int i = 0; i < text1.length; i++) {
            char[] ch = text1[i].toCharArray();//将此字符串转换为新的字符数组
            for (int j = 0; j < ch.length/2; j++) {
                char temp = ch[j];
                ch[j] = ch[ch.length-1-j];
                ch[ch.length-1-j] = temp;
            }
            //返回成字符串
            text1[i] = String.valueOf(ch);
            s += text1[i] + " ";
        }
        System.out.println(s);
    }
public static void main(String[] args) {
        String text = "I like writing code best";
        Task01 task01 = new Task01();
        task01.alphabeticalReversal(text);
}
  1. String s="name=王五 age=18 classNum=1101”;将上面的字符串中包含的信息存放到Student(里面有 name,age, classNum 三个属性)的对象中:
public class Student {
    String name;
    String age;
    String classNum;

    public void save(Student student,String s){
        //先取出来,再放进去
        String[] strs = s.trim().split(" ");
        for (int i = 0; i < strs.length; i++) {
            strs[i] = strs[i].substring((strs[i].indexOf("="))+1);

        }
        student.setName(strs[0]);
        student.setAge(strs[1]);
        student.setClassNum(strs[2]);
        System.out.println(student.toString());

    }

//省略get、set、tostring方法

    public Student() {
    }

    public Student(String name, String age, String classNum) {
        this.name = name;
        this.age = age;
        this.classNum = classNum;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值