您的位置:首页 > 职场人生

剑指Offer-【面试题04:替换空格】

2016-11-18 16:49 459 查看
package com.cxz.question4;
/*
* 请实现一个函数,把字符串中的每个空格替换成"%20",例如“We are happy.”,则输出“We%20are%20happy.”
* 原来一个空格字符,替换成%20,字符串会变长
* */
public class Demo4 {

/**
*
* @param string 要转换的字符数组
* @param usedLength 字符数组中已经使用的长度,没转换之前的
* @return 转换后的字符数组长度,-1表示处理失败
*/
public static int replaceBlank(char[] string, int usedLength) {
//判断输入是否合法
if (string == null || string.length < usedLength) {
return -1;
}

//统计字符数组中的空白字符数
int whiteCount = 0;
for (int i = 0; i < usedLength; i++) {
if (string[i] == ' ') {
whiteCount++;
}
}

//计算转换后的字符长度
int targetLength = whiteCount * 2 +usedLength;
int tmp = targetLength;
if (targetLength > string.length) {
return -1;
}

if (whiteCount == 0) {
return usedLength;
}

usedLength--;
targetLength--;

//字符中有空白字符,一直处理到所有的空白字符处理完
while (usedLength >= 0 && usedLength < targetLength) {
if (string[usedLength] == ' ') {
string[targetLength--] = '0';
string[targetLength--] = '2';
string[targetLength--] = '%';
} else {
string[targetLength--] = string[usedLength];
}
usedLength--;
}
return tmp;
}

public static void main(String[] args) {
char[] string = new char[50];
string[0] = 'W';
string[1] = 'e';
string[2] = ' ';
string[3] = 'a';
string[4] = 'r';
string[5] = 'e';
string[6] = ' ';
string[7] = 'H';
string[8] = 'a';
string[9] = 'p';
string[10] = 'p';
string[11] = 'y';

int length = replaceBlank(string, 12);
System.out.println(new String(string, 0, length));
}

}

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: