cc150:字串:1.4
阿新 • • 發佈:2019-01-27
題目
程式設計寫程式,將空格全部替換為”%20”。假設字串尾部有足夠的空間存放字串。並且知道字串的長度
演算法
package com.ynu.www.tool;
public class ReplaceBlank {
private static String testString = "hellow new world!";
// 計算字串中包含的空格個數
public static int getBlankNum(String testString) {
int count = 0;
for (int i = 0; i < testString.length(); i++) {
String tempString = String.valueOf(testString.charAt(i));
if (tempString.equals(" ")) {
count++;
}
}
return count;
}
// 列印char[]陣列
public static void printArray(char[] testArray) {
for (char i : testArray) {
System.out.print(i);
}
System.out.println();
}
// 將字串空格轉換為20%
public static void replaceAllBlank(String testString) {
if (testString == null || testString.length() <= 0) {
return;
}
// 字元陣列初始長度
int length = testString.length();
// 字元陣列增加長度後
int newLength = newLength = getBlankNum(testString) * 2
+ testString.length();
char [] tempArray = new char[newLength];
System.arraycopy(testString.toCharArray(), 0, tempArray, 0, testString.toCharArray().length);
int indexofOriginal = length - 1;
int indexofNew = newLength - 1;
System.out.println("未替換空格時的字串:");
printArray(tempArray);
while (indexofOriginal >= 0 && indexofOriginal != indexofNew) {
if (tempArray[indexofOriginal] == ' ') {
tempArray[indexofNew--] = '%';
tempArray[indexofNew--] = '2';
tempArray[indexofNew--] = '0';
} else {
tempArray[indexofNew--] = tempArray[indexofOriginal];
}
indexofOriginal--;
}
System.out.println("替換空格後的字串:");
printArray(tempArray);
}
public static void main(String[] args) {
replaceAllBlank(testString);
}
}