String类
创建String字符串的常见方式
三种构造方法:
1.public String () 创建一个空白字符串,不包含任何内容
String str=new String();//说明字符串没有任何内容
System.out.println("第一个字符串:"+str);
2.public String(char[ ]array ) 根据字符数组的内容来创建对应的字符串
char[] charArray={'A','B','C'};
String str2=new String(charArray);
System.out.println("第二个字符串:"+str2);
3.public String (byte[ ] array) 根据字节数组内容来创建对应的字符串
byte[] byteArray={65,66,67};
String str3=new String(byteArray);
System.out.println("第三个字符串:"+str3);
一种直接创建:
String str="ABC";
备注:直接写上双引号,系统也会认定为字符串对象
常用方法
一、判断功能
1. public boolean equals(Object anObject)
将此字符串与指定对象进行比较,当且仅当该参数不为null,并且是于此对象表示相同字符序列的String对象时,结果才为true。不但进行地址判断,还进行内容判断,只要符合其中一个条件就返回true,建议:如果比较双方一个是常量,一个是变量,推荐把常量字符串放在前面,把变量放在后面,防止空指针异常
2. public boolean equalsIgnoreCase(String anotherString)
将此 String 与另一个 String 比较,不考虑大小写。如果两个字符串的长度相同,并且其中的相应字符都相等(忽略大小写),则认为这两个字符串是相等的。
二、获取功能
1. public int length()
返回字符串的长度
//初始化一个字符串对象
String str = "abcdefghijklmnopqrst";
//获取长度
int length = str.length();
System.out.println(length);
// 20
2. public String concat(String str)
将指定的字符串连接到该类的尾部
String str2="Hello";
String str3="World";
String concat=str2.concat(str3);
// HelloWorld
3. public char charAt(int index)
返回指定索引处的char值
char c="Hello".char(1);
// e
4. public int indexOf(String str)
返回指定子字符串第一次出现该字符串内的索引,有就返回索引值,否则返回-1
String str = "abcdefghijklmnopqrst";
int i=str.indexOf("rst");
// 17
5. public String substring(int beginIndex)
返回一个子字符串重beginIndex处开始截取该字符串到该字符串末尾
//字符串截取
String str4 = "HelloWorld";
//获取从W开始到最后所有内容
// 获取W的索引
int i1 = str4.indexOf("W");
String substring = str4.substring(i1);
6. public String substring(int begIndex,int endIndex)
返回一个字符串,从begIndex开始到endIndex结束,包含begIndex,不包含endIndex
//字符串截取
String str4 = "HelloWorld";
int i1 = str4.indexOf("W");
String substring1 = str4.substring(4, 8);
System.out.println(substring1);
三、转换功能
1.public char[ ]toCharArray()
将此字符转换成新的字符串数组
String str="HelloWorld";
char[] chars = str.toCharArray();
for (int i = 0; i < chars.length; i++) {
System.out.print(chars[i]+" ");
}
// H e l l o W o r l d
2. public byte[ ] getBytes()
使用平台默认的字符集将该字符串编码转换成新的字节数组
byte[] bytes = str.getBytes();
for (int i = 0; i < bytes.length; i++) {
System.out.println(bytes[i]);
}
//72
//101
//108
//108
//111
//87
//111
//114
//108
//100
**3.public String replace(CharSequence target,CharSequence replacement) **
将与target匹配的字符串使用replacement字符串替换掉(将老的字符串转换成新的字符串),返回的是新的字符串。
//字符串内容的转换
String str2="Nice to meet you";
// 把str2中出现的o换成*
String o = str2.replace("o", "*");
System.out.println(o);
// Nice t* meet y*u