当前位置:网站首页>剑指Offer05. 替换空格
剑指Offer05. 替换空格
2022-07-03 11:50:00 【伍六琪】
剑指Offer05. 替换空格
请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = "We are happy."
输出:"We%20are%20happy."
限制:
0 <= s 的长度 <= 10000
JAVA代码
工具类方法
在这里列举一下,但是不可以投机取巧哦~~
class Solution {
public String replaceSpace(String s) {
return s.replace(" ","%20");
}
}

官方办法
通过将字符串转为字符数组的方法,逐个字符分析该字符串,如果是空格就向数组中插入% 2 0 三个字符,如果不是空格就将该位置字符直接插入数组中。
注意:不能直接arr.toString()转为字符串,会乱码。
new String(源头数组,起始位置,终止位置)
class Solution {
public String replaceSpace(String s) {
char[] arr = new char[s.length()*3];
int index = 0;
for(int i = 0;i<s.length();i++){
if(s.charAt(i)==' '){
arr[index++] = '%';
arr[index++] = '2';
arr[index++] = '0';
}else{
arr[index++] = s.charAt(i);
}
}
String newStr = new String(arr,0,index);
return newStr;
}
}
解决问题的思路非常重要。
边栏推荐
- Recovery of website address and method of Amazon account login two-step verification failure caused by mobile phone number becoming empty
- Systemverilog-- OOP--对象的拷贝
- 4000字超详解指针
- Fluent: Engine Architecture
- 023(【模板】最小生成树)(最小生成树)
- 为什么我的mysql容器启动不了呢
- Dart: view the dill compiled code file
- Is it OK to open an account for online stock speculation? Is the fund safe?
- 雲計算未來 — 雲原生
- 网络通讯之Socket-Tcp(一)
猜你喜欢

Is BigDecimal safe to calculate the amount? Look at these five pits~~

云计算未来 — 云原生

Integer string int mutual conversion

Download address and installation tutorial of vs2015

Quantitative calculation research

Solve msvcp120d DLL and msvcr120d DLL missing

Display time with message interval of more than 1 minute in wechat applet discussion area

为什么我的mysql容器启动不了呢

PHP导出word方法(一mht)

Itext7 uses iexternalsignature container for signature and signature verification
随机推荐
网上炒股开户安不安全?谁给回答一下
Optimize interface performance
Swagger
New features of ES6
02_ Lock the code, and don't let the "lock" become a worry
225. Implement stack with queue
Pragma pack syntax and usage
LeetCode 0556. Next bigger element III - end of step 4
JVM memory model
Redis 笔记 01:入门篇
How to deploy web pages to Alibaba cloud
PHP get the file list and folder list under the folder
2020-09_ Shell Programming Notes
SLF4J 日志门面
【mysql专项】读锁和写锁
repo Manifest Format
Implement verification code verification
Adult adult adult
2.9 overview of databinding knowledge points
Dart: view the dill compiled code file