把字符串中空格替换为"%20"

package com.nwsuaf.test;

public class Test3 {
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);
}

}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值