JAVA语言中 String 类的应用(上)

1.字符与字符串之间的转换

 

对应代码如下: 

public class Test{
	
	public static void main(String[] args){
		String str = "helloworld";
		System.out.println(str.charAt(0));//取得指定索引位置的字符
		char[] data = str.toCharArray();//将字符串变为字符数组返回
		for(int i = 0;i<data.length;i++){
			System.out.print(data[i]);
		}
		System.out.println();
		System.out.println(new String(data));//将字符数组全部转为字符串
		System.out.println(new String(data,5,5));//将字符数组第五位开始转换,转换五位
	}
}

对应结果为: 

 

对于方法 charAt(),若对应参数不在字符串范围之内会出现字符串长度越界的异常. 

2.字节与字符串之间的转换: 

 

对应代码为: 

public class Test{
	
	public static void main(String[] args){
		String str = "helloworld";
		byte[] data = str.getBytes();//将字符串转变为字符数组
		for(int i = 0;i<data.length;i++){
			System.out.print(data[i]+"  ");
		}
		System.out.println();
		System.out.println(new String(data));//将字节数组转化为字符串
	}
}

对应结果为: 

 

通过上面程序以及结果可知,字节并不适合处理中文,字节适合.字节只适合处理二进制. 

3.字符串比较: 

 

对应代码如下: 

public class Test{
	
	public static void main(String[] args){
		String str1 = "helloworld";
		String str2 = "HELLOWORLD";
		System.out.println(str1.equals(str2));//区分大小写
		System.out.println(str1.equalsIgnoreCase(str2));//不区分大小写
		System.out.println("a".compareTo("A"));//字符串之间的比较
		System.out.println("a".compareTo("a"));
		System.out.println("AB".compareTo("AC"));
		System.out.println("冯".compareTo("彭"));
		
	}
}

对应结果为: 

 

由上图结果可知,对于compareTo()方法,返回值为整型,改方法会根据对应数据大小返回三种内容:

1.相等:返回0 ;

2.小于:返回小于0的负数 ;

3.大于:返回大于0的正数 ;

同时对于compareTo()方法,区分大小写

猜你喜欢

转载自blog.csdn.net/Summer___Hui/article/details/88577888