Java String 常用API练习

package String;

public class Test {
	public static void main(String[] args) {
		//String类型的构造方法
		
		String s1 = new String();//创建一个空的字符串对象
		System.out.println(s1);
		
		byte[] bytes = new byte[]{'1','2','3'};
		String s2 = new String(bytes);
		System.out.println(s2);
		String s3 = new String(bytes, 0, 2);
		System.out.println(s3);
		
		char[] value = new char[]{'a','b','c','d'};
		String s4 = new String(value);
		System.out.println(s4);
		String s5 = new String(value, 0, 3);
		System.out.println(s5);
		
		String s6 =  new String("SB");
		System.out.println(s6);
		
		//字符串的方法
		
		String s7 = new String("abcdefg");
		int len = s7.length(); //字符串的长度
		System.out.println(s7+" 长度: "+len);
		
		//求字串
		String sub1 = s7.substring(1);//从下标1 往后的字串
		System.out.println(sub1);
		String sub2 = s7.substring(1,2);//初始下标1 末尾下标3的字串(不包含末尾下标)
		System.out.println(sub2);
		
		//字符串是否以指定字符串开头
		boolean f1 = s7.startsWith("abc");//s7 是否以abc 开头
		System.out.println( s7 +"	以abc开头??	"+f1);
		boolean f2= s7.startsWith("demo");//s7是否以demo开头
		System.out.println( s7 +"	以demo开头??	"+f2);
		
		//字符串是否以指定字符串结尾
		boolean f3 = s7.endsWith("fg"); //s7 是否以fg结尾
		System.out.println( s7 +"	以fg结尾??	"+f3);
		
		//字符串中是否包含另一个字符串
		boolean f4 = s7.contains("abc");
		System.out.println(s7 +"   包含abc ??" +f4);
		
		//字符串包含另一个字符串的第一次初始位置
		int index = s7.indexOf("bcd");//如果包含返回下标,如果不包含返回-1
		int index1  = s7.indexOf("demo");
		System.out.println("bcd在"+s7+"中的下标是 "+index);
		System.out.println("demo在"+s7+"中的下标是 "+index1); 
		
		//比较两个字符串是否相同
		if(s6 instanceof String){
			boolean f5 = s7.equals(s6);
			System.out.println(s7+"    "+s6+"  这两个字符串相同吗?? "+f5);
		}
		
		//判断字符串是否为空串
		System.out.println(s7+" 是否为空串??"+s7.isEmpty());
		
		//获取字符串指定位置上的字符
		System.out.println(s7+" 坐标为3上的字符是? "+s7.charAt(3));
		
		//将小写转为大写
		String bigS7 = s7.toUpperCase();
		System.out.println(s7+" 转大写 "+bigS7);
		
		//将大写转为小写
		System.out.println(bigS7+" 转小写 "+bigS7.toLowerCase());

		//在字符串中,将给定的旧字符串用新字符替换
		System.out.println(s7.replace('b', 'B'));
		
		//在字符串中,将给定的旧字符串,用新字符串替换
		System.out.println(s7.replaceFirst("abc", "ABC"));
		
		//去除字符串两端空格
		String s8 = new String("        hello  world      ");
		System.out.println(s8);
		String s9 = s8.trim();
		System.out.println(s9);
	}

}

猜你喜欢

转载自blog.csdn.net/weixin_34873452/article/details/88897428