字符串的实战应用1

题目
来源:牛客网
第一行输入一个文本串 S 。
第二行输入字符串 A 。
第三行输入字符串 B 。
|S|为S的长度,|A|为A的长度,|B|为B的长度,所有字符都是小写字母,保证 |A| <= |S| 。
对于50%的数据:1<= |A|、|B|、|S| <=1000
对于100%的数据:1<= |A|、|B|、|S| <=1000000

输入
abababcd
ab
cd
输出
cdcdcdcd

题解:

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        StringBuilder str = new StringBuilder(s);
        String a = scan.next();
        String b = scan.next();
        int i;
        while ((i = str.indexOf(a)) != -1) {
            str.replace(i, i + a.length(), b);
        }
        System.out.println(str.toString());
    }
}

总结:
此题主要学习了indexof()和replace()的用法,indexof()查找了字符串a在调用此方法的字符串中的位置并返回,如果未找到,则返回-1;replace()方法中,指定开头和结尾位置,并用指定的字符串替换。

查询API:

indexof()常用的两种方法:
indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
.
int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
从字符串的指定位置(fromIndex)开始寻找指定子串。

replace()常用的方法
replace(char oldChar, char newChar)
Returns a string resulting from replacing all occurrences of oldChar in this string with newChar.
.
replaceAll(String regex, String replacement)
Replaces each substring of this string that matches the given regular expression with the given replacement.
replaceAll()方法中,可一次性将指定子串全部替换,故代码也可这样写:

import java.util.Scanner;
public class Main{
    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);
        String s = scan.next();
        String a = scan.next();
        String b = scan.next();
        s = s.replaceAll(a,b);
        System.out.println(s);
    }
}

这样使得代码更加的简洁,但从运行结果看,占用的内存更多了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值