【Java】编写一个方法,将字符串中的空格全部替换为“ ”

58 篇文章 0 订阅

编写一个方法,将字符串中的空格全部替换为“%20”,假定该字符串尾部有足够的空间存放新增字符,并且知道字符串的真实长度。

因为java里字符串是不可变的,所以如果用java,用字符数组而不是字符串

从后往前放不用担心数据覆盖问题

<span style="font-family:Microsoft YaHei;">public class replaceSpaces {
	public void spacesReplace(char[] str, int length)
	{
		int spaceCount = 0, newLength;
		for( int i = 0; i < length; i++)
		{
			if (str[i] == ' ')
				spaceCount++;
		}
		newLength = length + spaceCount*2;
		str[newLength] = '\0';
		for(int i = length -1; i >= 0; i--)
		{
			if(str[i] == ' ')
			{
				str[newLength - 1] = '0';
				str[newLength - 2] = '2';
				str[newLength - 3] = '%';
				newLength = newLength - 3;
			}	
			else
			{
				str[newLength - 1] = str[i];
				newLength = newLength - 1;
			}
		}
	}
}
</span>

测试用例:

1. 输入的字符串包含空格(空格位于字符串的最前面,最后面,中间,连续多个空格)

2. 输入的字符串没有空格

3. 特殊输入测试(字符串是null,字符串是空字符串,字符串只有一个空格,字符串只有连续多个空格)


举一反三:

有两个排序的数组A1和A2,在A1的末尾有足够多的空余空间容纳A2。请实现一个函数,把A2中的所有数字插入到A1中并且所有数字是排序的。

还是从后往前插入,需要注意的是如果A1的元素比A2的少,比较完成后A2还有一部分元素需要依次插入A1

#include<iostream>
using namespace std;

void insertString(char A1[], char A2[], int length1, int length2) {
	if (A1 == NULL || A2 == NULL || length1 < 0 || length2 < 0) {
		return;
	}
	int newlength = length1 + length2;
	int index1 = length1 - 1;
	int index2 = length2 - 1;
	while(index1 >=0 && index2 >= 0) {
		if (A1[index1] > A2[index2]) {
			A1[newlength - 1] = A1[index1];
			index1--;
			newlength--;
		}
		else if (A1[index1] < A2[index2]) {
			A1[newlength - 1] = A2[index2];
			index2--;
			newlength--;
		}
		else {
			A1[newlength - 1] = A2[index2];
			A1[newlength - 2] = A1[index1];
			index1--;
			index2--;
			newlength -= 2;
		}
	}
	
	if(length1 < length2) {
		for( int i = index2; i >= 0; i--) {
			A1[newlength - 1] = A2[index2];
		}
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值