字符串的构造方法
字符串的特点:
- 字符串是常量;它们的值在创建之后不能更改。字符串缓冲区支持可变的字符串。例如:
String str = "abc";
等效于:
char data[] = {'a', 'b', 'c'}; String str = new String(data);
-
因为 String 对象是不可变的,所以可以共享。
-
字符串底层相当于用一个字节byte数组来存储相关的值
常见3种构造方法
public String ():空白字符
public String (char []array):根据字符数组创建字符串
public (byte []array)
获取功能的方法
public int length():返回此字符串的长度
public String concat(String str):将指定的字符串连接到该字符串的末位
//实际上可以直接拼接 str1+""+str2
public char charAt(int index):返回指定索引处的char值
pubic int indexOf(String str):返回指定字符串第一次出现在该字符串 的索引
public String substring(int beginIndex):返回一个子字符串,该字符串从beginIndex开始截取字符串到字符串结尾。
public String substring(int beginIndex,int endIndex):返回指定索引区间的字符串
转换功能的方法
pubic char toCharArray():将此字符串转化为新的字符数组
public String replace(String a,String b) :将与a匹配的字符串使用b字符串替换
public void reverse() :将字符串反转
分割功能的方法
注意:转义字符前必须加上\
“.$|()[{^?*+\”
pubilc String[]split(String regex):以regex规则拆分为字符数组
String s="abcdef"
String[]array=s.split("bc");
//array[]:{"a","def"}
案例分析
String类字符串的拼接:
利用concat方法从头到尾添加
例子:将String[] arr={“Hello”,“the”,“wolrd”};拼接成[Hello the world]格式
package com.qustion;
public class Stringtest {
public static void main(String[] args) {
String[] arr={"Hello","the","wolrd"};
String res=ArrayToString(arr);
System.out.println(res);
}
public static String ArrayToString(String[] arr){//这里的方法需设置为static
String s=new String("[");
for(int i=0;i<arr.length;i++){
if (i< arr.length-1){
s=s.concat(arr[i]+" ");//返回的是一个Sring 需要s这个字符串来接受
}else {
s=s.concat(arr[i]+"]");
}
}
return s;
}
}
//输出结果为[Hello the World]
判断是否为大小写
if(ch>='A'&&ch<='Z') {
bigCount++;
}else if(ch>='a'&&ch<='z') {
smallCount++;
}e