当前位置:网站首页>剑指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;
}
}
解决问题的思路非常重要。
边栏推荐
- Integer string int mutual conversion
- 网络通讯之Socket-Tcp(一)
- 145. Post order traversal of binary tree
- Qt+vtk+occt reading iges/step model
- Flutter Widget : KeyedSubtree
- Itext7 uses iexternalsignature container for signature and signature verification
- 【嵌入式】---- 内存四区介绍
- 4000字超详解指针
- Introduction to concurrent programming (II)
- 023(【模板】最小生成树)(最小生成树)
猜你喜欢
4000字超详解指针
Colleagues wrote a responsibility chain model, with countless bugs
Quantitative calculation research
Wechat applet - basic content
C language improvement article (wchar_t) character type
Solve msvcp120d DLL and msvcr120d DLL missing
Socket TCP for network communication (I)
云计算未来 — 云原生
Integer string int mutual conversion
Integer int compare size
随机推荐
Flutter: self study system
laravel 时区问题timezone
DEJA_ Vu3d - cesium feature set 053 underground mode effect
Dart: view the dill compiled code file
Socket TCP for network communication (I)
225. Implement stack with queue
Slf4j log facade
Shell: basic learning
adb push apk
Talk about the state management mechanism in Flink framework
使用BLoC 构建 Flutter的页面实例
Kubernetes three dozen probes and probe mode
PHP导出word方法(一mht)
SLF4J 日志门面
MySQL time zone solution
Is BigDecimal safe to calculate the amount? Look at these five pits~~
Prompt unread messages and quantity before opening chat group
2.9 overview of databinding knowledge points
Redis notes 01: Introduction
Dart: about grpc (I)