String的常用操作

String的常用操作

字节数组--->字符串


>    public class Test {
>     	public static void main(String[] args) {
>     		String str ="adcde";	
>     		byte[] bs = str.getBytes();//将字符串变成byte类型数组
>     		String str1 = new String(bs,0,5);//将0~5的字符数组重新变为String
>     		String str2 = new String(bs);//将全部的字符数组重新变为String
>     		System.out.println(str1);
>     		System.out.println(str2);
>       	}
>   }

判断是否以指定的字符串开头或结尾:
•判断是否以指定的字符串开头:public boolean startsWith(String prefix)
•判断是否以指定的字符串结尾:public boolean endsWith(String suffix)
•范例:

public class Test {
	public static void main(String[] args) {
		String str ="**adcde##";	
		System.out.println(str.startsWith("**"));
		System.out.println(str.endsWith("##"));
	}	
}

替换操作:

使用以下方法能完成替换操作:

public String replaceAll(String regex, String replacement)

•范例:

public static void main(String[] args) {
		String str ="hello world";	
		String str1 = str.replaceAll("l", "x");
		System.out.println(str1);
	}	
 输出结果为:hexxo worxd

字符串截取:

使用以下方法完成字符串截取操作:
•全部截取:

public String substring(int beginIndex)

•部分截取:

public String substring(int beginIndex,int endIndex)

•范例

public static void main(String[] args) {
		String str ="hello world";	
		String str1 = str.substring(6);
		String str2 = str.substring(0, 5);
		System.out.println(str1);
		System.out.println(str2);
	}
输出结果为 :   
str1=world;
str2=hello;	

字符串拆分:

可以将字符串按照指定的内容进行拆分:

public String[] split(String regex)

•范例:按照空格进行拆分

public static void main(String[] args) {
		String str ="hello wlord";	
		String[] split = str.split(" ");
		for (String string : split) {
			System.out.println(string);
		}
	}

字符串查找:

在字符串中查找指定的内容是否存在用以下方法:
1:取得指定字符串的位置

public int indexOf(int ch)

此方法返回值为int类型,如果找到则返回位置,如果找不到则返回-1

•范例:

public static void main(String[] args) {
		String str ="hello wlord";	
		System.out.println(str.indexOf("hello"));
		System.out.println(str.indexOf("csdn"));
	}

2:直接查找

public boolean contains(String s)

•范例:

public static void main(String[] args) {
	String str ="hello wlord";	
	System.out.println(str.contains("hello"));
	System.out.println(str.contains("csdn"));
} 
  1. 字符串的其他操作

    取得字符串的长度: public int length()
                  
    去掉左右两边空格: public String trim()
                  
    转大写 public String toUpperCase()
                  
    转小写 public String toLowerCase()
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值