当前位置:网站首页>单 词替换
单 词替换
2022-08-02 03:33:00 【小艾菜菜菜】
题目描述:
输入一个字符串,以回车结束(字符串的长度不超过100)
该字符串由若干个单词组成,单词之间用空格隔开,所有的单词区分大小写。
现在需要将其中的某个单词替换成另一个单词,并输出替换之后的字符串。
输入格式:
输入共3行。
第一行:是包含多个单词的字符串s;
第二行:是待替换的单词a;
带三行:是a将被替换的单词 b;
输出格式:
共一行,将输出的s 中所有的单词a替换成b之后的字符串。
输入样例:
You want someone to help you
You
I
输出样例:
I want someone help you
解题方法:
我们使用 java 的 split 方法先将输入的字符串以空格隔开,然后遍历所有的字符,寻找与第二个将要替换的字符相匹配的位置,并将其替换掉
不过需要我们另外的开辟新的数组空间来存储被替换后的字符串
代码实现:
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
ArrayList<String> arr = new ArrayList<>();
String str = sc.nextLine();
String odStr = sc.nextLine();
String newStr = sc.nextLine();
for(String retavl : str.split(" ")){
if(odStr.equals(retavl)){
arr.add(newStr);
}else{
arr.add(retavl);
}
}
System.out.println(String.join(" ",arr)); //这里还原了,用空格连接起来
}
}
边栏推荐
- 如何使用 PHP 实现网页交互
- 字符串匹配(蛮力法+KMP)
- 【LeetCode】Add the linked list with carry
- Comparative analysis of mobile cloud IoT pre-research and Alibaba Cloud development
- 【Connect the heart rate sensor to Arduino to read the heart rate data】
- 谷粒商城10——搜索、商品详情、异步编排
- openwrt RK3568_EVB移植
- 【plang 1.4.5】编写坦克(双人)游戏脚本
- MPU6050 accelerometer and gyroscope sensor is connected with the Arduino
- 引擎开发日志:集成Bullet3物理引擎
猜你喜欢
随机推荐
2020 - AAAI - Image Inpainting论文导读《Learning to Incorporate Structure Knowledge for Image Inpainting》
UKlog.dat和QQ,微信文件的转移
Application of electronic flow on business trip
IDEA2021.2安装与配置(持续更新)
学习(四):显示FPS,和自定义显示调试
笔记本电脑充电问题
Based on the raspberry pie smart luggage development environment set up
如何用 Lightly 进行 Debug 断点调试?
谷粒商城10——搜索、商品详情、异步编排
读取FBX文件踩坑清单
Lightly 支持 Markdown 文件在线编写(文中提供详细 Markdown 语法)
滑动窗口方法
MPU6050 accelerometer and gyroscope sensor is connected with the Arduino
使用飞凌嵌入式IMX6UL-C1板子——qt+opencv环境搭建
【LeetCode】Add the linked list with carry
引擎开发日志:集成Bullet3物理引擎
STM32 CAN 介绍以及相关配置
【MQ-3 Alcohol Detector and Arduino Detect Alcohol】
GM7150,振芯科技,视频解码器,CVBS转BT656/601,QFN32,替换TVP5150/CJC5150
【plang 1.4.4】编写茶几玛丽脚本









