/**
*题目:请实现一个函数,把字符串中的每个空格替换成”%20”。例如输入“We are happy.”,则输出”We%20are%20happy.”
*时间:2015年8月25日10:34:31
*文件:ReplaceBlank.java
*作者:cutter_point
*/
package bishi.Offer50.y2015.m08.d25;
public class ReplaceBlank
{
public static char[] ReplaceBlank(char string[], int length)
{
//我们用倒序的方法进行遍历
if(string == null && length < 0)
{
System.err.println("数据异常");
return null;
}
//我们先求出需要的空间长度
int originalLength = length;
int numberOfBlank = 0; //空白的字符
int i = 0;
while(i < length)
{
if(string[i] == ' ')
{
++numberOfBlank;
}
++i;
}
//我们需求的长度'
int newLength = originalLength + numberOfBlank * 2;
if(newLength > length)
{
//我们为新的数组申请空间
char string2[] = new char[newLength];
//然后把数据移到新的数组中
for(int j = 0; j < length; ++j)
string2[j] = string[j];
string = string2;
}
//我们从后往前遍历,把所有的字符进行替换
int indexOfnewString = newLength - 1;
int indexOfOriginalString = length - 1;
while(indexOfnewString >= indexOfOriginalString && indexOfOriginalString > -1)
{
//如果是空格我们就替换,如果不是,就直接复制过来
if(string[indexOfOriginalString] == ' ')
{
string[indexOfnewString--] = '0';
string[indexOfnewString--] = '2';
string[indexOfnewString--] = '%';
}//if
else
{
string[indexOfnewString--] = string[indexOfOriginalString];
}
--indexOfOriginalString;
}//while
return string;
}
public static void test()
{
String ss = "We are happy.";
char s[] = new char[50];
s = "We are happy.".toCharArray();
s = ReplaceBlank(s, s.length);
for(int i = 0; i < s.length; ++i)
{
System.out.print(s[i]);
}
}
public static void main(String[] args)
{
test();
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
原文地址:http://blog.csdn.net/cutter_point/article/details/47976575