1 字符与字符串的相互转换
字符串就是一个字符数组,所以在String类里面支持有字符数组转为字符串以及字符串转为字符的操作方法。
//取得字符串长度:public int length();
//数组的长度:数组名.length;
1.1 将字符数组转为字符串
用String类的构造方法!
/**
1. public String(char [] value);将字符数组value中的所有内容变为字符串
2. public String(char [] value,int offset,int count);将字符数组value中的部分内容变为字符串
offset为开始索引、count为个数
均为成员方法,通过对象调用!!!
*/
public class Test{
public static void main(String[] args)
{
//静态初始化一个字符串数组
char [] arr = new char[]{
'h','e','l','l','o','&','1','3','1','4'};
//将字符数组中的所有内容变为字符串
String str1=new String(arr);
System.out.println(str1);
//从下表为5的索引开始,将之后的5个字符变为字符串
String str2=new String(arr,5,5);
System.out.println(str2);
//如果,字符的个数超出了数组的范围,运行时会有数组越界异常(StringIndexOutOfBoundsException)
String str3=new String(arr,5,10);
System.out.println(str3);
}
}
1.2 将字符串转为字符数组
/**
将字符串该为字符数组
1. public char[] tocharArray();
*/
public class Test{
public static void main(String[] args)
{
String str="hello";
char [] result=str.toCharArray();
//for-each循环
for(char i:result)
{
System.out.print(i+" ");
}
}
}
1.3 将字符串转为单个字符
/**
1. public char charAt(int index);取得指定索引位置上的字符
index:索引
*/
public class Test{
public static void main(String[] args)
{
//取得索引为0的位置的字符
System.out.println("hello".charAt(0));
//如果索引越界,会报数组越界异常StringIndexOutOfBoundsException
System.out.println("hello".charAt(6));
}
}
1.4 判断一个字符串是否由数字组成?
/**
判断一个字符串是否由数组组成
取得字符串长度:public int length();
取得数组的长度:数组名.length
*/
public class Test{
public static boolean isNumber1(String str)
{
for(int i=0;i<str.length();i++)
{
//将字符串根据索引转成单个字符
char result=str.charAt(i);
if(result<'0'||result>'9')
{
return false;
}
}
return true;
}
public static boolean isNumber2(String str)
{
//将字符串转为字符数组
char [] data=str.toCharArray();
for(int i=0;i<data.length;i++)
{
if(data[i]<'0'||data[i]>'9')
{
return false;
}
}
return true;
}
public static void main(String[] args)
{
String str="14263";
System