天天看点

C++和C对字符串操作总结

一 c语言的字符串

c语言中没有字符串这个数据类型,用两种方法来表示字符串,第一种是字符数组char s[],第二种是字符指针char *s, 两者有区别,不能任务是一样的,区别如下(不完整,后期再慢慢补充)

1 初始化和赋值

char[]字符串赋值c语言中可以用“=”对字符串初始化,但是不能用“=”对其赋值,否则会出现类似于如下的错误:

error: incompatible types in assignment of ‘const char **’ to ‘char **’
           

如果要对c字符串赋值可以使用strcpy()函数。

char *定义的是字符串常量,不能对其修改除非使用new对其重新分配内存.但是可以对定义的指针修改,如下:

int len_c;
// char[]
char msg[] = "hello c";
//msg = "hello c string";  //错误
strcpy(msg,  "hello string");  //正确

//char*
char *s = "hwllo"; //编译器版本高的时候此处可能会有警告,加上const即可,因为这是定义了字符串常量
s = "hello"; // 对指针重定义,允许
s[] = "e" //对字符串常量修改,不允许
           

2 求c字符串的长度/strlen和sizeof的区别

函数: size_t strlen ( const char * str )

头文件: string.h

c语言字符串结尾会自动添加一个‘\0’表示字符串结束,strlen是计算从字符串开始到‘\0’的长度,结果有可能不固定。

比如char s[10], strlen(s)的结果可能不是固定的,视编译器而定,如果char s[10] = {‘\0’},strlen(s)为0

sizeof()返回的是变量声明后所占的内存数,不是实际长度,此外sizeof不是函数,仅仅是一个取字节运算符

3 c字符串常用操作

puts() 输出

char c[] = “aa”;

puts(c);

gets() 输入

char gt[15];

gets(gt);

strcat()字符串连接函数

char a1[10] = “hello”;

char a2[10] = “c”;

strcat(a1, a2);

strcpy() 字符串复制

char a1[10];

char a2[10] = “hello c”;

strcpy(a1, a2);

a2为”hello c”

strcmp()字符串比较,按照ASCALL码的大小逐个比较两个字符数组中的各个字符,知道出现不相同的或者遇到结束符

strcmp(字符数组1,字符数组2);

相等返回0

字符数组1大于2返回正整数

字符数组1小于2返回负数

strlen()返回字符串实际长度

二 c++中string的操作

1 取子串substr(),包含头文件string、iostream

原型string substr (size_t pos = 0, size_t len = npos) const;

从源字符串中的下标为pos的地方获取长度为npos的长度,如果第二个参数为空,则代表从pos一直获取到字符串结束。

例:

std::string str="We must keep out mind in study";
std::string str2 = str.substr (,);  // "must"
std::string str3 = str.substr (pos);  // from "must" to the end
std::cout << str2 << ' ' << str3 << '\n';
           

注意它的返回值是string类型,如果要赋给char []类型需要转换。

2 拷贝

strcpy()

memcpy()

三、类型转换

1 整型数转为字符串:char *itoa(int value, char *str, int radix)

itoa为interger to array的简称,value为整型,str为转换后的字符串,radix为进制数。

2 字符串转为整型数:int atoi(const char *nptr)

nptr为要转化你的字符串,返回值是转换后的整型。

3 字符转为整数

char a = ‘9’;

int k = a - ‘0’;

4 整数转为字符

int i = 5;

char ch = i + ‘0’;

继续阅读