1.先看一段代码,分析运行结果
int stringFunc()
{
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.in");
if(str3 == str4)
printf("str3 and str4 are same . in");
else
printf("str3 and str4 are not same. ln") ;
return 0;
}
分析:
1.str1和str2是两个字符串数组的首地址,我们会为它们分配两个长度为12个字节的空间,并把"hello world"的内容分别复制到数组中去。这是两个首地址不同的数组,因此str1和str2的值也不相同,所以输出的第一行是"str1 andstr2 are not same”。
2.str3和str4是两个指针,我们无须为它们分配内存以存储字符串的内容,而只需要把它们指向"hello world”在内存中的地址就可以了。由于"hello world”是常量字符串,它在内存中只有一个拷贝,因此str3和str4指向的是同一个地址。所以比较str3和str4的值得到的结果是相同的,输出的第二行是”str3 and str4 are same”。
面试题3:替换空格
题目:请实现一个函数,把字符串中的每个空格替换成”%20"。例如输入“We are happy.”,则输出“We%20are%%20happy."
解法1尾部插入:
void replaceBlankBack(char *string, int originalLength)
{
if (string == NULL && originalLength <= 0)
return;
int numberofBlank = 0;
int i = 0;
while (string [i] != '\0') {
if(string[i]== ' ')
++numberofBlank;//字符串包含空格的数量
++i;
}
/*newLength为把空格替换成'%20'之后的长度*/
int newLength = originalLength + numberofBlank * 2 + 1;
char *dest_string = (char *)malloc(newLength);
int indexofOriginal = originalLength;
int indexofNew = newLength - 1;
while(indexofOriginal >=0 && indexofNew >= indexofOriginal) {
if (string[indexofOriginal] == ' ') {
dest_string[indexofNew--] = '0';
dest_string[indexofNew--] = '2';
dest_string[indexofNew--] = '%';
}
else {
dest_string[indexofNew--] = string[indexofOriginal];
}
indexofOriginal--;
}
printf("\ndest_string: %s\n", dest_string);
free(dest_string);
dest_string = NULL;
}
解法2头部插入
void replaceBlankFront(char *string, int originalLength)
{
if (string == NULL && originalLength <= 0)
return;
int numberofBlank = 0;
int i = 0;
while (string [i] != '\0') {
if(string[i]== ' ')
++numberofBlank;//字符串包含空格的数量
++i;
}
/*newLength为把空格替换成'%20'之后的长度*/
int newLength = originalLength + numberofBlank * 2 + 1;
char *dest_string = (char *)malloc(newLength);
int indexofNew = 0;
i = 0;
while(i < originalLength) {
if (string[i] == ' ') {
dest_string[indexofNew++] = '0';
dest_string[indexofNew++] = '2';
dest_string[indexofNew++] = '%';
}
else {
dest_string[indexofNew++] = string[i];
}
i++;
}
printf("\ndest_string: %s\n", dest_string);
free(dest_string);
dest_string = NULL;
}
考点:
1.考查对字符串的编程能力。
2.考查对内存覆盖是否有高度的警惕。
3.考查指针的运用