String的API使用

String的API使用

char charAt(int index); 获取指定下标的字符

		// 下标从0-length
		String s = "hello world";
		char a1 = s.charAt(0);
		System.out.println(a1);// h

int length(); 获取长度

        int len = s.length();
		for (int i = 0; i < len; i++) {
			System.out.print(s.charAt(i));
		}
		// hello world

String concat(String str); 拼接 类似字符+

		String a2 = s.concat(" jack");
		System.out.println(a2);// hello world jack
		System.out.println("hi ".concat("jack ").concat("how are you"));// hi jack how are you

boolean contains(String str);判断字符串str是否存在true或false

		System.out.println(s.contains("hello"));// true

int indexOf(String str); 获取第一次出现str的下标值0-length,如果没有出现则返回-1

常用if (str.indexOf(“xxx”) != -1) 做包含判断

		System.out.println(s.indexOf("he"));// 0
		System.out.println(s.indexOf("sherry"));// -1

int lastIndexOf(); 返回最后一次出现的xx

		System.out.println(s.lastIndexOf("l"));// 9

boolean startWith();判断是否以xx开始

		System.out.println(s.startsWith("hel"));// true

boolean endWith();判断是否以xx结束

		System.out.println(s.endsWith("hel"));// false

boolean equals() ; 字符串值的判断

		String s1 = new String("hello world");
		System.out.println(s.equals(s1));// true
		System.out.println(s.equals("sherry"));// flase

byte[] getBytes(charset); 字符串转字节数组

		byte[] s3 = s.getBytes();
		for (byte b : s3) {
			System.out.print((char)b);
		}// hello world

char[] toCharArray(); 字符串转字符数组

		char[] s2 = s.toCharArray();
		for (char c : s2) {
			System.out.print(c);
		}// hello world

String[] split(regex); 按照正则,拆分数组

		String s4 = "ni,hello,good,nice";
		String[] s5 = s4.split(",");
		for (String str : s5) {
			System.out.println(str);
		}// ni
		//hello
		//good
		//nice

String.join/String对象.join(符号, string[]); 把数组按照符号组合起来

		String s6 = String.join("--", "java","is","good");
		System.out.println(s6);// java--is--good

String replace(String old, String new); 把old换成new

		String s7 = s.replace("hello", "hi");
		System.out.println(s7);// hi world

String replaceAll(String regex, String new) 把符合正则的换成new;

		String s8 = s4.replaceAll(",", "--");
		System.out.println(s8);// ni--hello--good--nice

String substring(int beginIndex, int endIndex); [beginIndex, endIndex) 截取字符串从0开始算的

		String s10 = s.substring(0, 6);
		System.out.println(s10);// hello 

String substring(int beginIndex);截掉字符串从1开始算的

		String s9 = s.substring(6);
		System.out.println(s9);// world

String trim(); 去除前后所有空格

		String s11 = new String("      前后还有空格嘛           ");
		System.out.println(s11.trim());// 前后还有空格嘛

String valueOf(xxxxx); 别的类型转换为String

		System.out.println(s.valueOf('a'));// a
		System.out.println(s.valueOf(true));// true
		System.out.println(s.valueOf(3.14));// 3.14
		System.out.println(s.valueOf("abcdefg"));// abcdefg
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值