例题:
#include<stdlib.h>
#include<stdio.h>
int main(){
char str1[]="hello world";
char str2[]="hello world";
char *str3="hello world";
char *str4="hello world";
if(str1==str2)
printf("str1 is same as str2\n");
else
printf("str1 not same as str2\n");
if(str3==str4)
printf("str3 is same as str4\n");
else
printf("str3 not same as str4\n");
system("pause");
return 0;
}
输出的结果应该是:
str1 is not same as str2
str3 is same as str4
解释:
str1和str2是两个字符串组,我们会为他们分配两个长度为12个字节的空间,并把"hello world"的内容分别复制到数组中去。这是两个初始地址不同的数组,因此str1和str2的值也不同,所以输出的第一行是str1 is not same as str2。
str3和str4是两个指针,我们无须为他们分配内存以存储字符串的内容,而只需要把它们指向“hello world”在内存中的地址即可。由于“hello world”是常量字符串,它在内存中只有一个拷贝,因此str3和str4指向的是同一地址。所以比较str3和str4的值得到的结果是相同的,输出的第二行是“str3 is same as str4”
替换空格操作:
题目:请实现一个函数,把字符串中的每个空格替换成“%20”。例如输入“we are happy”,则输出“we%20are%20happy”。
代码如下:
void replaceblank(char string[],int length){
if(string == NULL || length==0){
return;
}
int original_length =0;
int numofblank=0;
int i=0;
//搜索整体字符串的长度和空格的个数
while(string[i]!='\0'){
original_length++;
if(string[i]==' ')
++numofblank;
i++;
}
//算出转换之后的字符串的长度
int newlength = original_length + numofblank*2;
if(newlength > length)
return;
int indexoforiginal = original_length;
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--;
}
}
解析:
从字符串的后面开始复制和替换。首先准备两个指针,P1和P2。P1指向原始字符串的末尾,而P2指向替换之后的字符串的末尾。接下来向前移动指针P1,逐个把它指向的字符复制到P2指向的位置,知道碰到第一个空格为止。碰到第一个空格之后,把P1向前移动1格,在P2之前插入字符串%20.由于%20长度为3,同时也要把P2向前移动3格。