java中怎么使用substring截取字符串?

  • 该方法适用于所有品牌的电脑。

在处理字符串的过程中有很多情况下会遇到需要截取字符串的情况,这个时候使用Java中提供的substring方法来截取就非常方便了

其中比较经常使用到的方法有两个:

① public String substring(int beginIndex)

这个方法截取的字符串是从索引beginIndex开始的,到整个字符串的末尾,例如:字符串String s = "abcdef";

调用s.substring(2)表示从字符串的索引2开始截取到整个字符串结束,截取的字符串为cdef

② public String substring(int beginIndex, int endIndex)

这个方法截取的字符串从beginIndex开始,到字符串索引的endIndex - 1结束,即截取的字符串不包括endIndex这个索引对应的字符,所以endIndex的最大值为整个字符串的长度,所以使用这个方法的时候需要特别注意容易发生字符串截取越界的问题

下面是具体的代码:

import java.util.Scanner;
public class Main {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		String s = sc.nextLine();
		System.out.println(s.substring(0, 2));
		System.out.println(s.substring(2));
		sc.close();
	}
}

从控制台输入:saahdfasgfdga

1.png-600

以上就是java中怎么使用substring截取字符串?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他答疑