当前位置:网站首页>剑指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;
}
}
解决问题的思路非常重要。
边栏推荐
- Apprendre à concevoir des entités logicielles réutilisables à partir de la classe, de l'API et du cadre
- Talk about the state management mechanism in Flink framework
- Lambda expression
- Redis 笔记 01:入门篇
- [learning notes] DP status and transfer
- Visual studio 2022 downloading and configuring opencv4.5.5
- PHP export word method (one MHT)
- 2020-10_ Development experience set
- Use bloc to build a page instance of shutter
- Shutter: add gradient stroke to font
猜你喜欢

【附下载】密码获取工具LaZagne安装及使用
![[MySQL special] read lock and write lock](/img/ac/e01c26882cc664ea2e5e731c5a8bab.png)
[MySQL special] read lock and write lock

Colleagues wrote a responsibility chain model, with countless bugs

Self made pop-up input box, input text, and click to complete the event.
![[official MySQL document] deadlock](/img/2d/04e97d696f20c2524701888ea9cd10.png)
[official MySQL document] deadlock

Talk about the state management mechanism in Flink framework

PHP導出word方法(一mht)

The future of cloud computing cloud native

PHP导出word方法(一mht)

Implement verification code verification
随机推荐
win10 上PHP artisan storage:link 出现 symlink (): Protocol error的解决办法
Redis
Solve msvcp120d DLL and msvcr120d DLL missing
init. RC service failed to start
New features of ES6
Flutter: about monitoring on flutter applications
DEJA_ Vu3d - cesium feature set 053 underground mode effect
Unicode encoding table download
云计算未来 — 云原生
【嵌入式】---- 内存四区介绍
During FTP login, the error "530 login incorrect.login failed" is reported
Basic knowledge of OpenGL (sort it out according to your own understanding)
AOSP ~ NTP (Network Time Protocol)
C language improvement article (wchar_t) character type
PHP export word method (phpword)
Differences between MySQL Union and union all
Prompt unread messages and quantity before opening chat group
Socket TCP for network communication (I)
111. Minimum depth of binary tree
Cloud Computing future - native Cloud