当前位置:网站首页>剑指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;
}
}
解决问题的思路非常重要。
边栏推荐
- DEJA_VU3D - Cesium功能集 之 054-模拟火箭发射全过程
- Use bloc to build a page instance of shutter
- Flutter: self study system
- 1-2 project technology selection and structure
- 023(【模板】最小生成树)(最小生成树)
- Laravel time zone timezone
- 01_ Using the concurrent tool class library, is thread safety safe
- Adult adult adult
- 网上炒股开户安不安全?谁给回答一下
- QT OpenGL texture map
猜你喜欢

New features of ES6

网络通讯之Socket-Tcp(一)

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

Pki/ca and digital certificate

(构造笔记)ADT与OOP

实现验证码验证

Integer int compare size

What is more elegant for flutter to log out and confirm again?

During FTP login, the error "530 login incorrect.login failed" is reported
![[MySQL special] read lock and write lock](/img/ac/e01c26882cc664ea2e5e731c5a8bab.png)
[MySQL special] read lock and write lock
随机推荐
pragma-pack语法与使用
JVM内存模型
New features of ES6
The future of cloud computing cloud native
Implement verification code verification
If you can't learn, you have to learn. Jetpack compose writes an im app (I)
Fundamentals of concurrent programming (III)
Wechat applet pages always report errors when sending values to the background. It turned out to be this pit!
PHP導出word方法(一mht)
Shutter: add gradient stroke to font
Use of atomicinteger
网上炒股开户安不安全?谁给回答一下
Redis
Qt+vtk+occt reading iges/step model
Basic knowledge of OpenGL (sort it out according to your own understanding)
1-1 token
Unicode查询的官方网站
Shutter: about inheritedwidget
239. Sliding window maximum
If you can't learn, you have to learn. Jetpack compose writes an im app (II)