Java基础之String类

String 类:

1.特点:

1.字符串不变:字符串的值在创建后不能被更改。

2.因为String对象是不可变的,所以它们可以被共享。(即内存中只创建了一个对象,可以被多个使用)。

3.String字符串相当于一个数组,String底层是靠字符数组实现的。

2.构造方法

1.无参构造:

String str = new String();

2.通过字符数组构造

char chars【】= {a,b,c};

String str01 = new String(chars);

3.通过字节数组构造

byte bytes【】 = {97,98,99}

String str02 = new String(bytes);

3.常用方法

1.判断功能的方法:equals()与 equalsIgnoreCase()

代码演示:

public static void main(String[] args) {
		/*判断功能的方法:.equals():将此字符串与指定对象进行比较
					.eaualsIgnoreCase():将此字符串与指定字符串对象进行比较,忽略字母大小写
*/
		//创建字符串对象
		String s1 = "hello";
		String s2 = "hello";
		String s3 = "HELLO";
		
		System.out.println(s1.equals(s2));//true
		System.out.println(s1.equals(s3));//false
		System.out.println("========================");
		
		
		System.out.println(s1.equalsIgnoreCase(s2));//true
		System.out.println(s1.equalsIgnoreCase(s3));//ture
}

2.获取功能的方法:

.length():返回字符串的长度

.concat():将指定字符串连接到该字符串的末尾

.charAt():返回指定索引处的char值

.indexOf():返回指定子字符串第一次出现在该字符串内的索引

.subString(int  beginIndex) 返回一个字符串,从beginIndex开始截取,直至结尾

代码演示:

public static void main(String[] args) {
    //创建字符串对象
    String s = "helloworld";
​
    // int length():获取字符串的长度,其实也就是字符个数
    System.out.println(s.length());
    System.out.println("--------");
​
    // String concat (String str):将将指定的字符串连接到该字符串的末尾.
    String s = "helloworld";
    String s2 = s.concat("**hello");
    System.out.println(s2);// helloworld**hello
​
    // char charAt(int index):获取指定索引处的字符
    System.out.println(s.charAt(0));
    System.out.println(s.charAt(1));
    System.out.println("--------");
​
    // int indexOf(String str):获取str在字符串对象中第一次出现的索引,没有返回-1
    System.out.println(s.indexOf("l"));
    System.out.println(s.indexOf("owo"));
    System.out.println(s.indexOf("ak"));
    System.out.println("--------");
​
    // String substring(int start):从start开始截取字符串到字符串结尾
    System.out.println(s.substring(0));
    System.out.println(s.substring(5));
    System.out.println("--------");
​
    // String substring(int start,int end):从start到end截取字符串。含start,不含end。
    System.out.println(s.substring(0, s.length()));
    System.out.println(s.substring(3,8));
  }

3.分割功能的方法:

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

代码演示:

        String n = "wo@ai@ni";
		String g[] = n.split("@");
		for(int j = 0;j<g.length;j++) {
			System.out.print(g[j]+"  ");
		}

猜你喜欢

转载自blog.csdn.net/XianYuZong/article/details/82143461