字符串中空格的替换
方法1 临时数组
创建临时数组,用于存放原字符串的复制与替换结果
注:1.创建的临时数组大小取最大值即原字符串数组大小的三倍
2.创建索引 index ,这样每次赋值只需要将index自加即可,例如 c[index++] = '%';
3.寻找字符串中特定位字符方法: char c0 = s.charAt(i);
4.将字符数组转化为字符串的方法: String newStr = new String(c, 0, index);
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param s string字符串 * @return string字符串 */ public String replaceSpace (String s) { // write code here int length = s.length(); char[] c = new char[3*length]; int index = 0; for(int i=0; i<length; i++){ char c0 = s.charAt(i); if(c0 == ' '){ c[index++] = '%'; c[index++] = '2'; c[index++] = '0'; } else{ c[index++] = c0; } } String newStr = new String(c, 0, index); return newStr; } }