C风格字符串
序言:
尽管现代C++支持C风格字符串,但是不应该在C++程序中使用这个类型。C风格字符串常常带来许多的错误,是导致大量安全问题的根源!
C风格字符串可以理解为是“以空字符null结尾的数组”.
[cpp] view plain copy print ?
-
- char strErr[] = {'C','+','+'};
- char strOk[] = "C++";
//请注意下面两条语句的区别
char strErr[] = {'C','+','+'};
char strOk[] = "C++";
正文:
1、C++通过(const)char*类型的指针来操纵C风格字符串。
[cpp] view plain copy print ?
- const char *str = "some values";
-
-
-
-
- while (*str)
- {
- cout << *str;
- ++ str;
- }
const char *str = "some values";
/*
*如果str所指的字符串不是以null结尾,那么循环调用会失败,
*循环从str指向的位置开始读数,直到内存中某处null结束符为止
*/
while (*str)
{
cout << *str;
++ str;
}
2、C风格字符串的标准库函数:strncat,strncpy
1)在使用C风格字符串的标准库函数时,一定不要忘记字符串一定要以null结尾!
[cpp] view plain copy print ?
-
- char str[] = {'C','+','+'};
- cout << strlen(str) << endl;
//不会有好的结果...
char str[] = {'C','+','+'};
cout << strlen(str) << endl;
2)如果必须使用C风格字符串,则使用函数 strncat 和 strncpy 会比 strcat 和 strcpy 更加安全
[cpp] view plain copy print ?
- char largeStr[16 + 18 + 2];
-
- strncpy(largeStr,cp1,17);
-
-
-
-
- strncat(largeStr," ",2);
- strncat(largeStr,cp2,19);
char largeStr[16 + 18 + 2];
strncpy(largeStr,cp1,17);
/*
*在调用strncat时,原来用于结束largeStr的null被
*新添加的空格覆盖,然后在空格后面写入新的结束符null
*/
strncat(largeStr," ",2);
strncat(largeStr,cp2,19);
3、尽量使用string代替
一是提高了安全性,二是提高了效率!
[cpp] view plain copy print ?
-
-
- int main()
- {
- const char *cp = "hello";
- int cnt = 0;
-
- while (*cp)
- {
- ++cnt;
- cout << *cp;
- ++ cp;
- }
- cout << '\n' << cnt << endl;
- }
-
-
- int main()
- {
- const char *cp = "hello";
- int cnt = 0;
-
- while (cp)
- {
- ++cnt;
- cout << *cp;
- ++ cp;
- }
- cout << '\n' << cnt << endl;
- }
//P116 习题4.22 解释下面两个程序的区别
//(1)
int main()
{
const char *cp = "hello";
int cnt = 0;
while (*cp)
{
++cnt;
cout << *cp;
++ cp;
}
cout << '\n' << cnt << endl;
}
//(2)
int main()
{
const char *cp = "hello";
int cnt = 0;
while (cp)
{
++cnt;
cout << *cp;
++ cp;
}
cout << '\n' << cnt << endl;
}
[cpp] view plain copy print ?
-
- int main()
- {
- const char ca[] = {'H','e','l','l','o'};
- const char *cp = ca;
- cout << strlen(cp) << endl;
- while (*cp)
- {
- cout << *cp;
- ++ cp;
- }
- cout << endl;
- cout << strlen(ca) << endl;
- cout << strlen(cp) << endl;
- }