为了节省内存,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.
str1和str2是两个字符串数组,系统为他们分配了自定义大小的内存,并把字符串常量”hello world”复制到数组中去。str1和str2是两个初始化地址不同的数组,所以str1和str2的值不同。
str3和str4是两个指针,无需为它们分配内存存储字符串的内容,只需把它们指向”hello world”在内存中的地址即可。因此str3和str4的值相同。
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指针、字符串是个空字符串、字符串只有一个空格字符、字符串中只有连续多个空格)。