Java 实例 - 字符串搜索
以下实例使用了 string 类的 indexof() 方法在字符串中查找子字符串出现的位置,如过存在返回字符串出现的位置(第一位为0),如果不存在返回 -1:
//SearchStringEmp.java 文件public class SearchStringEmp{
public static void main(String[] args) {
String strOrig = "Hello readers";
int intIndex = strOrig.indexOf("Hello");
if(intIndex == - 1){
System.out.println("Hello not found");
}else{
System.out.println("Found Hello at index "
+ intIndex);
}
}}以上代码实例输出结果为:
Found Hello at index 0
字符串反转
以下实例演示了如何使用 Java 的反转函数 reverse() 将字符串反转:
public class StringReverseExample{
public static void main(String[] args){
String string="abcdef";
String reverse = new StringBuffer(string).
reverse().toString();
System.out.println("nString before reverse:
"+string);
System.out.println("String after reverse:
"+reverse);
}}以上代码实例输出结果为:
String before reverse:abcdef String after reverse:fedcba
▎ 删除字符串中的一个字符
以下实例中我们通过字符串函数 substring() 函数来删除字符串中的一个字符,我们将功能封装在 removeCharAt 函数中。
立即学习“Java免费学习笔记(深入)”;
实例代码如下:
//Main.java 文件public class Main {
public static void main(String args[]) {
String str = "this is Java";
System.out.println(removeCharAt(str, 3));
}
public static String removeCharAt(String s, int pos) {
return s.substring(0, pos) + s.substring(pos + 1);
}}以上代码实例输出结果为:
thi is Java
以上就是【JAVA实例】字符串搜索、反转、删除的内容,更多相关内容请关注PHP中文网(www.php.cn)!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号