深入理解strcpy
函数
函数参数解析
strcpy(目的字符数组地址, 源字符数组地址);
应用方式1
int main(void) {
char s1[81] = "China";
char s2[81] = "India";
strcpy(s1, s2); //s2 -> s1
puts(s1);
return 0;
//Output:India
}
应用方式2
int main(void) {
char s1[81] = "China";
char s2[81] = "India";
strcpy(s1 + 2, s2 + 1);
puts(s1);
return 0;
//Output:chndia
}
函数实现
void strcpy(char s1[], char s2[]) {
int i = 0, j = 0;
while (s2[i]) {
s1[j++] = s2[i++];
}
s1[j++] = s2[i++];
return;
}
优化
void strcpy(char s1[], char s2[]) {
int i = 0, j = 0;
+ while (s1[j++] = s2[i++]) {}
- while (s2[i]) {
- s1[j++] = s2[i++];
- }
- s1[j++] = s2[i++];
return;
}
注意:
- 兼顾函数的高可用性和易读性
- 赋值表达式做条件时,先赋值,后做条件
✦将一个顺序表作为两个顺序表使用
删除一个字符串中的某个字符
样例:
“mydoghasabook
” -> “mydghasabk
”
程序样例1:
int main(void) {
char s[] = "mydoghasabook";
char key = 'o';
int i = 0;
while (s[i]) {
if (s[i] - key) {
i++;
} else {
//删除语句
for (int j = i; s[j]; j++) {
s[j] = s[j + 1];
}
}
}
puts(s);
return 0;
}
优化
int main(void) {
char s[] = "mydoghasabook";
char key = 'o';
int i = 0;
while (s[i]) {
if (s[i] - key) {
i++;
} else {
//删除语句
s[i] = 0;
strcpy(s + i, s + i + 1);
//strcat(s, s + i + 1);
}
}
puts(s);
return 0;
}
程序样例2
int main(void) {
char s[] = "mydoghasabook";
char key = 'o';
int i = 0, j = 0;
while (s[i]) {
if (s[i] - key) {
s[j++] = s[i];
}
i++;
}
s[j] = 0;
puts(s);
return 0;
}
优化
int main(void) {
char s[] = "mydoghasabook";
char key = 'o';
int i = 0, j = 0;
while (s[j++] = s[i]) {
if (!(s[i++] - key)) {
j--;
}
}
puts(s);
return 0;
}
优化2
int main(void) {
char s[] = "mydoghasabook";
char key = 'o';
int i = 0, j = 0;
for (; !(s[i] - key) || (s[j++] = s[i]); i++) {}
puts(s);
return 0;
}