请实现一个函数,把字符串 s 中的每个空格替换成"%20"。
示例 1:
输入:s = “We are happy.”
输出:“We%20are%20happy.”
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ti-huan-kong-ge-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class Solution {
public String replaceSpace(String s) {
int n = s.length();
char arr[] = new char[n*3];//因为要替换成%20,所以创建三倍,后面数组转字符串再截取
int size = 0;
for(int i = 0;i < n;i++){
char c = s.charAt(i);//字符串取出
if(c == ' '){
arr[size ++] = '%';
arr[size ++] = '2';
arr[size ++] = '0';
}
else arr[size ++] = c;
}
String news = new String(arr,0,size);//char数组转string ,直接调用String 构造器
return news;
}
}