一.常用构造方法
package com.xiao.string;
import org.junit.Test;
/**
* @Author 笑笑
* @Date 19:47 2018/4/18
*/
//String类的构造方法
public class StringDemo {
//String(byte[] bytes) 传入一个字节数组,使用平台的默认字符集解码指定的 byte 数组,构造一个新的 String。
@Test
public void test_01(){
byte[] bytes = {97,98,99,100};
String str = new String(bytes);
//打印abcd
System.out.println(str);
}
//第一个数代表起始索引,第二个代表转换的个数
@Test
public void test_02(){
byte[] bytes = {97,98,99,100};
String str = new String(bytes,2,1);
//打印c
System.out.println(str);
}
//String(char[] value) 分配一个新的 String,使其表示字符数组参数中当前包含的字符序列。
@Test
public void test_03(){
char[] chars ={'a','b','c'};
String str = new String(chars);
//打印abc
System.out.println(str);
}
//第一个数代表起始索引,第二个代表个数
@Test
public void test_04(){
char[] chars ={'a','b','c'};
String str = new String(chars,1,1);
//打印b
System.out.println(str);
}
}
二.其他的一些方法
package com.xiao.string;
import org.junit.Test;
/**
* @Author 笑笑
* @Date 20:44 2018/4/18
*/
//String类中常用的方法
public class StringDemo_02 {
//返回字符串的长度
@Test
public void test_01(){
String a = "abc";
int length = a.length();
System.out.println(length);
}
//返回指定索引处的char值
@Test
public void test_02(){
String a = "abc";
char c = a.charAt(0);
//打印为a
System.out.println(c);
}
//substring(int beginIndex, int endIndex) 获取字符串的一部分,返回新字符串;[0,2)不包含第二个索引位置
@Test
public void test_03(){
String a = "abc";
String s = a.substring(0, 2);
//打印为ab
System.out.println(s);
}
//substring(int beginIndex) 返回新字符串,包含给定索引位置,及其之后的全部字符
@Test
public void test_04(){
String a = "abc";
String s = a.substring(1);
//打印为bc
System.out.println(s);
}
//replaceAll(String regex, String replacement)返回新的字符串
// 使用给定的 replacement 替换此字符串所有匹配给定的正则表达式的子字符串
@Test
public void test_05(){
String a = "a,b,c";
String s = a.replaceAll(",", "-");
//打印为a-b-c
System.out.println(s);
}
//toUpperCase()使用默认语言环境的规则将此 String 中的所有字符都转换为大写
@Test
public void test_06(){
String a = "abc";
String s = a.toUpperCase();
//打印为ABC
System.out.println(s);
}
//startsWith(String prefix) 返回boolean值 测试此字符串是否以指定的前缀开始
@Test
public void test_07(){
String a = "abc";
boolean b = a.startsWith("b");
//打印为false
System.out.println(b);
}
//toCharArray() 将此字符串转换为一个新的字符数组
@Test
public void test_08(){
String a = "abc";
char[] chars = a.toCharArray();
}
}