1.构造方法
public StringBuffer();无参构造
public StringBuffer(int capacity);指定容量的字符串缓冲区对象
public StringBuffer(String str);指定字符串内容的字符串缓冲区对象
2. 容量和(实际)长度
public int capacity()返回当前容量,理论值
public int length()返回当字符串实际长度
3. 添加功能
public StringBuffer append(String str);把任意数据类型的数据(8中基本数据类型、char数组、String、StringBuffer和Object)添加到字符串缓冲区里面,并返回字符串缓冲区本身
public StringBuffer insert(int offset,String str);在指定位置把任意数据类型的数据插入字符串缓冲区,并返回字符串缓冲区本身
4. 删除功能
public StringBuffer deleteCharAt(int index);删除指定位置的字符,并返回本身
public StringBuffer delete(int start,int end);删除从指定位置开始指定位置结束的内容,并返回本身
5. 替换功能
public StringBuffer replace(int start,int end,String str);在指定位置替换原有字符串
setCharAt(int index, char ch);
6. 翻转功能
public StringBuffer reverse();将此字符序列用其反转形式取代,返回对象本身
7. 截取功能
public String subString(int start);返回一个新的String
public String subString(int start,int end);返回一个新的String
8. 查找功能
public char charAt(int index);返回指定位置的字符
public int indexOf(String str);返回指定子字符串在原字符串的首次出现位置
public int indexOf(String str,int fromIndex);从指定位置开始,返回指定子字符串在原字符串的首次出现位置
public int lastIndexOf(String str);返回指定子字符串在原字符串的最后一次出现的位置
public int lastIndexOf(String str, int fromIndex);从指定位置开始,返回指定子字符串在原字符串的最后一次出现的位置位置
1.字符串对象一旦创建,就无法修改,每次字符串的改变,都会生成新的字符串。但是如果调用api方法后的字符串与原字符串 一 致,则不会生成新的字符串。
2.通过字面量、常量来初始化的字符串,会存放在常量池;new初始化的字符串,会存放在堆中
常量池的变迁:
jdk1.6以及之前:常量池存在于方法区中。jdk1.7,常量池放到了堆中。jdk1.8之后,常量池放到了元空间中
3. Integer.valueOf();
字符串不能强转为int型,需要通过Integer.valueOf();转换为int型
4.Scanner 中的sc.next();和sc.nextLine();的区别,next输入的时候一遇到空格就结束,但是nextLine(),遇到空格不结束
String API
https://docs.oracle.com/javase/9/docs/api/java/lang/String.html
转换(转https://blog.csdn.net/lizhensen/article/details/79394741)
1、字符串与字符数组之间的转换:
字符串转为字符数组:public char[] toCharArray()
字符数组转为字符串:public String(char[] value)
PublicString(char[] value,int offset,int count)
例:
public class StringAPIDemo01{
public static void main(String args[]){
String str1 = "hello" ; // 定义字符串
char c[] = str1.toCharArray() ; // 将一个字符串变为字符数组
for(int i=0;i
2、字符串与字节数组之间的转换:
字符串转字节数组:public byte[] getBytes()
字符数组转字符串:public String(byte[] bytes)
public String(byte[] bytes,int offset,int length)
例:
public class StringAPIDemo02{
public static void main(String args[]){
String str1 = "hello" ; // 定义字符串
byte b[] = str1.getBytes() ; // 将字符串变为byte数组
System.out.println(new String(b)) ; // 将全部的byte数组变为字符串
System.out.println(new String(b,1,3)) ; // 将部分的byte数组变为字符串
}
};
3、字符串与整型数组间的转换:
public class StringAPIDemo03
{public static void main(String[] args)
{//字符串转为整型数组:
String s1="123456789";
int n1[]=new int[s1.length()];
for(int i=0;i