数据结构-字符串

为了节省内存,C/C++把常量字符串放到一个单独的内存区域。当几个指针赋值给相同的常量字符串时,它们的实际上会指向相同的内存地址。但用常量内存初始化数组,情况却不同。

 

3.运行下列程序,得到的结果是什么?


 

#include <stdio.h>

int main(void){

	char str1[] = "hello world";
	char str2[] = "hello world";

	char* str3 = "hello world";
       	char* str4 = "hello world";

	if(str1 == str2)
		printf("str1 and str2 are same.\n");
	else
		printf("str1 and str2 are not same.\n");

	if(str3 == str4)
		printf("str3 and str4 are same.\n");
	else
		printf("str3 and str4 are not same.\n");

	return 0;	
}


结果:

str1 and str2 are not same.

str3 and str4 are same.

 

str1str2是两个字符串数组,系统为他们分配了自定义大小的内存,并把字符串常量hello world复制到数组中去。str1str2是两个初始化地址不同的数组,所以str1str2的值不同。

str3str4是两个指针,无需为它们分配内存存储字符串的内容,只需把它们指向hello world在内存中的地址即可。因此str3str4的值相同。

 

 

4.请实现一个函数,把字符串中的每个空格替换成“%20.例如输入“We are happy.”,则输出“We%20are%20happy.”。

 

W

e

 

a

r

e

 

h

a

p

p

y

.

\0

 

 

 

 

p1              p2

 

W

e

 

a

r

e

 

h

a

p

p

h

a

p

p

y

.

\0

    p1               p2   

 

W

e

 

a

r

e

 

h

%

2

0

h

a

p

p

y

.

\0

   p1       p2                 

 

W

e

 

a

r

a

r

e

%

2

0

h

a

p

p

y

.

\0

         p1       p2             

 

W

e

%

2

0

a

r

e

%

2

0

h

a

p

p

y

.

\0

p1p2  

 

 


 
/* length为字符数组string的总容量 */
void ReplaceBlank(char string[], int length){

	if(string == NULL || length <= 0)
		return;

	/* originalLength 为字符串string的实际长度 */
	int originalLength = 0;
	int numberOfBlank = 0;
	int i = 0;
	while(string[i] != '\0'){
		++originalLength;

		if(string[i] == ' ')
			++numberOfBlank;

		++i;
	}

	/* newLength 为把空格替换成'%20'之后的长度 */
	int newLength = originalLength + numberOfBlank * 2;
	if(newLength > length)
		return;

	int indexOfOriginal = originalLength;
	int indexOfNew = newLength;
	while(indexOfOriginal >= 0 && indexOfNew > indexOfOriginal){
	
		if(string[indexOfOriginal] == ' '){
		
			string[indexOfNew--] = '0';
			string[indexOfNew--] = '2';
			string[indexOfNew--] = '%';
		}else{
		
			string[indexOfNew--] = string[indexOfOriginal];
		}
		--indexOfOriginal;
	}
}

 

测试用例:

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

2)输入的字符串中没有空格。

3)特殊输入测试(字符串是个NULL指针、字符串是个空字符串、字符串只有一个空格字符、字符串中只有连续多个空格)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值