目录
String字符串
- 特点
- 字符串,java程序中所有字符串字面值。
- final修饰,表示不可变的字符序列。
- 字符串的值在创建之后不能被改变。
- 常用方法:
String o = " 123456789 ";
String u = " abc ";
System.out.println(o.length());//字符串长度
System.out.println(o.charAt(2));//索引处字符串
System.out.println(o.isEmpty());//是否为空
System.out.println(o.toLowerCase());//转小写
System.out.println(o.toUpperCase());//转大写
System.out.println(o.trim());//忽略首位空格
System.out.println(o.equals(u));//判断是否相同
System.out.println(o.equalsIgnoreCase(u));//判断是否相同,忽略大小写
System.out.println(o.concat("0"));//尾部添加
System.out.println(o.compareTo(u));//比较大小
System.out.println(o.substring(2));//截取指定位置到最后
System.out.println(o.substring(2, 6));//截取指定开始,指定结束
System.out.println(o.replace("1", "11"));//字符串替换
System.out.println(o.indexOf("4"));//首次出现的位置
System.out.println(o.startsWith(" 123"));//判断是否以指定前缀开始
System.out.println(o.endsWith("2131"));//判断是否以指定后缀结束
System.out.println(o.contains("345"));//判断是否包含
String[] split = o.split("6");//字符串切割
包装类
基本数据类型 | 包装类 |
byte | Byte |
short | Short |
int | Integer |
long | Long |
double | Double |
float | Float |
boolean | Boolean |
char | Character |
StringBuffe & StringBuilder
- 特点
- StringBuffer:可变的字符序列、效率低、线程安全。
- StringBuilder:可变的字符学列、效率高、线程不安全。
- 常用方法
StringBuffer sb = new StringBuffer("12345");
System.out.println(sb);
sb.reverse();//反转
System.out.println(sb);
sb.append("678");//添加
System.out.println(sb);
sb.delete(1, 4);//删除,含左不含右
System.out.println(sb);
sb.replace(1, 3, "234566");//替换
System.out.println(sb);
//String中一些常用方法StringBuffer中也能用到
//StringBuffer 与 StringBuilder用法相同
String、基本数据类型、包装类的相互转换
- String ——> 基本数据类型 / 包装类
- 使用 XXX.pasrsexxx() 方法
String str = "10";
Integer in = Integer.parseInt(str);
String str1 = "11.11";
Double do = Double.parseDouble(str1);
- 包装类 ——> 基本数据类型
- 自动拆箱
- 包装类中的 XXX.xxxValue() 方法
Intager in = new Integer("123");
//自动拆箱
int i = in;
//Value 方法
int i1 = in.intValue();
- 基本数据类型 ——> 包装类
- 自动装箱
- 构造器
- 使用 XXX.valueOf() 方法
int i = 11;
//自动装箱
Intager in = i;
//构造器
Intager in1 = new Intager(i);
//valueOf 方法
Intager in2 = Intager.valueOf(i);
- 基本 / 包装 ——> String
- 字符串的构造器
- 调用包装类中的 toString() 方法
- 字符串中的 String.ValueOf() 方法
int i = 123;
//toString 方法
String str = S.toString();
//valueOf 方法
String str1 = String.valueOf(i);
字符串和字节、字符数组之间的转换
- 字符串 <——> 字符数组
- 转字符数组:toCharArray( )
- 转字符串:new String(Char[] 字符数组)
//字符串 ——> 字符数组
String str = "ABCDE";
char[] c = str.toCharArray();
//字符数组 ——> 字符串
String s = new String(c);
- 字符串 <——> 字节数组
- 转字节数组:getBetys( )
- 转字符串:new String(byte[] 字节数组)
//字符串 ——> 字节数组
String str = "ABCDEF";
byte[] b = str.getBytys();
//字节数组 ——> 字符串
String s = new String(b);