学习字符串之后,我们知道字符串内部包含一个字符数组,而String也可以使用已知的方法很方便的和char[]与byte[]相互转换。
【1.】字符和字符串
首先我们看一下字符和字符串之间相互转换。
1.1 String(char[] value) 构造方法
public class Demo1 {
public static void main(String[] args) {
char[] arr = {'q','w','e','r','t'};
System.out.println(new String(arr));
}
}
该代码的运行结果为:qwert。
观察代码,大家可以看到小九在打印输出的时候使用了构造方法new String();
在字符串转化为字符的过程中,构造方法内部必须是一个字符数组【即:char value[]】。
另外,该构造方法还可以增加范围属性,实现将部分字符数组中的内容变成字符串。
1.2 String(char[] value,int offset,int count)构造方法
我们可以看到上面代码将构造方法内的属性改成了new String(arr,0,3);
在这种方式下得到的输出是qwe。
该方法中的offset代表的是该字符数组是从哪个下标开始转化为字符串,相应的,count指的是字符数组转化为字符串的结束下标。
形如new String(char value[], int offset, int count)
就代表要把字符数组value从下标为offset到下标count的元素转化为字符串进行输出。
1.3 charAt(int index) 方法
该方法的作用是取得索引位置的字符,索引从0 开始,即:index的取值是字符串数组的下标数值。
例:获取指定位置的字符
1.4 toCharArray() 方法
该方法的作用是,将字符串变为字符数组返回
例:字符串与字符数组的转换
public static void main(String[] args) {
String s = "hello Word";
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
System.out.print(ch[i] + " ");
}
}
toCharArray()方法的返回值是一个char数组,要使用char[] 来接收,然后就可以将字符串转换成一个字符数组,然后依次遍历。
【代码示例】:给定一个字符串,判断其是否全部由数字所组成
要判断字符串是否全部由数字组成,我们首先要将这个字符串转化成一个字符数组,然后再依次遍历,判断字符数组元素是否为数字。
public static void main(String[] args) {
String s = "239980f";
System.out.println(isNumber(s));
String s1 = "646131";
System.out.println(isNumber(s1));
}
public static boolean isNumber(String s){
char[] ch = s.toCharArray();
for (int i = 0; i < ch.length; i++) {
if(ch[i] < '0' || ch[i] > '9'){
return false;
}
}
return true;
}
【2.】字节和字符串
【2.1】getBytes()方法
该方法的返回值是一个byte数组,要定义一个byte[]类型的变量来存储。
【例1】:实现字符串与字节数组的转换处理。
【2.2】String(byte[] bytes)构造方法
将一个byte数组的所有元素转换为String类型。
例:
public static void main(String[] args) {
byte[] bytes = {'a','b','c','d','e'};
System.out.println(new String(bytes));
}
【2.3】String(byte[] bytes,int offset,int length)构造方法
将byte数组下标为offset到length的元素转换为String类型。
例:
public static void main(String[] args) {
byte[] bytes = {'a','b','c','d','e'};
System.out.println(new String(bytes,1,3));
}