String类常用方法使用二

String类常用方法使用 一
String类常用方法使用 二
String类常用方法使用 三

2.5提取部分字符串的方法

这里写图片描述


2.5.1:获取指定索引位置的字符

使用charAt()方法可以指定索引处的字符返回。

package com.dong.test;

public class StringTest {
	public static void main(String[] args) {
		String s1 = new String("hello Word");
		char s = s1.charAt(4);
		System.out.println(s);
	}
}

运行结果:

o


2.5.2:获取字符串

通过字符串的下标进行截取,且下标是从0开始的。

  1. substring(int beginIndex):返回的是从指定索引位置开始截取直到该字符串结尾的子串。
  2. substring(int beginIndex,int endIndex):返回的是从字符串某一索引位置开始截取至某一个索引位置的子串。
package com.dong.test;

public class StringTest {
	public static void main(String[] args) {
		String s1 = new String("hello Word");
		
		System.out.println(s1.substring(2));
		System.out.println(s1.substring(2,7));
	}
}

第一个输出截取的是 从下标为2的字符到原字符串是s1的结尾
第二个输出截取的是 s1中下标从2到7的字符串

运行结果:

llo Word
llo W


2.5.3:连接连个字符串

concat()方法

package com.dong.test;

public class StringTest {
	public static void main(String[] args) {
		String s1 = new String("hello Word");
		
		s1 = s1.concat("happy!");
		System.out.println(s1);
	}
}

运行结果:

hello Wordhappy!


2.5.4:字符串的替换

replace():该方法可以实现将指定的字符或者字符串替换成新的字符或者字符串。

package com.dong.test;

public class StringTest {
	public static void main(String[] args) {
		String s1 = new String("hello Word");
		
		s1=s1.replace("hello", "hi");
		System.out.println(s1);
	}
}

运行结果:

hi Word


2.5.5:去除空格

trim():该方法返回的是字符串的副本,忽略前导的空格和尾部的空格。

package com.dong.test;

public class StringTest {
	public static void main(String[] args) {
		String s1 = new String("hello Word   ");
		
		s1=s1.trim();
		System.out.println(s1);
		System.out.println(s1.length());
	}
}

运行结果:

hello Word
10

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值