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 函数中。
实例代码如下:
//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实例】字符串搜索、反转、删除的内容。