String 类

String类在java.lang包中,java使用String类创建一个字符串变量,字符串变量属于对象。

java把String类声明的final类,不能有类。String类对象创建后不能修改,由0或多个字符组成,包含在一对双引号之间。

String类对象的创建
字符串声明:String stringName;
字符串创建:stringName = new String(字符串常量);或stringName = 字符串常量;

String类具有丰富的方法计算字符串的长度、比较字符串、连接字符串、提取字符串

length()方法:

String类提供了length()方法,确定字符串的长度返回字符串中的字符数

public class StringDemo {
    public static void main(String args[]) {
        String site = "www.kgc.com";
        int len = site.length();
        System.out.println( "网址长度 : " + len );
   }
}

 

equals()方法:

String类提供了equals( )方法,比较存储在两个字符串对象的内容是否一致

==”和equals()有什么区别?

equals():检查组成字符串内容的字符是否完全一致

==:判断两个字符串在内存中的地址,即判断是否是同一个字符串对象

equalsIgnoreCase()方法 不分大小写比较

toLowerCase()方法 全部小写

toUpperCase()方法 全部大写

public static void main(String[] args) {
        String str1 = "abc";
        String str2 = "ABC";
        char [] arrayA = new char [] {'a','b','c'};
        String str3 = new String(arrayA);
、
       System.out.println(str1.equals(str2));//false
        System.out.println(str1.equals(str3));//true
        System.out.println("abc".equals(str1));//true
————————————————

字符串连接:

方法1:使用“+”

方法2:使用String类的concat()方法

String str = "aa".concat("bb").concat("cc");
相当于String str = "aa"+"bb"+"cc";

字符串常用提取方法:

方法名说明
public int indexOf(int ch) 搜索第一个出现的字符ch(或字符串value),如果没有找到,返回-1
public int indexOf(String value)  
public int lastIndexOf(int ch) 搜索最后一个出现的字符ch(或字符串value),如果没有找到,返回-1
public int lastIndexOf(String value)  
public String substring(int index) 提取从位置索引开始的字符串部分
public String substring(int beginindex, int endindex) 提取beginindex和endindex之间的字符串部分
public String trim() 返回一个前后不含任何空格的调用字符串的副本

 

1 String str = "I am a good student";
2 int a = str.indexOf('a');//a = 2
3 int b = str.indexOf("good");//b = 7
4 int c = str.indexOf("w",2);//c = -1
5 int d = str.lastIndexOf("a");//d = 5
6 int e = str.lastIndexOf("a",3);//e = 2

字符串拆分:

String类提供了split()方法,将一个字符串分割为子字符串,结果作为字符串数组返回】

1 String str = "asd!qwe|zxc#";
2 String[] str1 = str.split("!|#");//str1[0] = "asd";str1[1] = "qwe";str1[2] = "zxc";

StringBuffer类:

对字符串频繁修改(如字符串连接)时,使用StringBuffer类可以大大提高程序执行效率

StringBuffer声明

StringBuffer strb = new StringBuffer();

StringBuffer strb = new StringBuffer("aaa");

StringBuffer的使用

sb.toString();           //转化为String类型

sb.append("");      //追加字符串
sb.insert (1, ""); //插入字符串

String是不可变对象经常改变内容的字符串最好不要使用StringStringBuffer是可变的字符串字符串经常改变的情况可使用StringBuffer,更高效JDK1.5后提供了StringBuilder,等价StringBuffer

 

posted @ 2020-06-07 16:49  南山i南  阅读(241)  评论(0)    收藏  举报