字符串中的每个空格替换

题目:请实现一个函数,把字符串中的每个空格替换成"%20"。如"we are happy."->"we%20are%20happy."

分析:

方法(1):先统计空格,再开辟新空间,拷数据填%20,拷数据

void replace_black1(char arr[], int n)
{
	//先统计有多少个空格
	int count = 0;
	for (int i = 0; i < n; i++)
	{
		if (arr[i] == ' ')
		{
			count++;
		}
	}
   
	char* new_arr = (char*)malloc(sizeof(char)*n + count * 2);
	int new_index = 0;
	for (int i = 0; i < n; i++)
	{
		if (arr[i] == ' ')
		{
			new_arr[new_index++] = '%';
			new_arr[new_index++] = '2';
			new_arr[new_index++] = '0';
		}
		else
		{
			new_arr[new_index++] = arr[i];
		}
	}
	new_arr[new_index] = '\0';
	strcpy(arr, new_arr);
}

方法(2),传参时直接让数组空间大一点,算好空格个数,直接从后到前在原数组上拷贝。(从前到后会覆盖)

void replace_black2(char arr[], int n)
{
	if (arr == NULL || n <= 0)
	{
		return;
	}
	//统计空格次数
	int black_count = 0;
	for (int i = 0; i < n; i++)
	{
		if (arr[i] == ' ')
		{
			black_count++;
		}
	}

	int new_end = n + 2 * black_count;//新尾
	int end = n;//旧尾
	//以上这种位置连通'\0'一起拷贝
	while (end >= 0)
	{
		if (arr[end] != ' ')
		{
			arr[new_end--] = arr[end--];
		}
		else
		{
			arr[new_end--] = '0';
			arr[new_end--] = '2';
			arr[new_end--] = '%';
			end--;
		}
	}
}

方法(3):用一个新的string对象ret接收数据,若在原串中遇到非空格字符,将其+=到ret后面,若在原串中遇到空格字符,将"%20"加等到后面

void replace_black3(string& s)
{
	string ret;
	for (int i = 0; i < s.size(); i++)
	{
		if (s[i] != ' ')
		{
			ret = ret + s[i];
		}
		else
		{
			ret = ret + "%20";
		}
	}
	s = ret;
}

猜你喜欢

转载自blog.csdn.net/lyl194458/article/details/88829938