c风格字符串
字符串常量:
1.字符数组 继承自c语言
用字符数组存储字符串
例子:
char str[8] = [‘p’,’r’, ‘o’, ‘g’, ‘r’, ‘a’, ‘m’, ‘\0’]; 忘了添加\0 程序会出错
char str[8] = “program”;
char str[] = “program”;
缺点
1.连接拷贝比较要调库函数
2.当字符串长度不确定时候,要new 动态创建字符数组 还要delete。
3.字符串
但是要求能看懂别人的c风格字符串
const char * ptr = “program”;
2.string
建议用这个,拼接和赋值很方便,可以用下标访问,类似字符数组。
第八章string类重载了 运算符
string s2;
cin >> s2 ; //输入多少个字符都可以,不会越界 >>提取运算符
strlen 字符串有效长度,到\0长度,不包含\0
例子程序,比较c字符串操作和c++ string:
转载出处:https://www.cnblogs.com/metaphors/p/9409153.html
1. 使用strcat进行字符串拼接
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *firstName = "Theo";
char *lastName = "Tsao";
char *name = (char *) malloc(strlen(firstName) + strlen(lastName));
strcpy(name, firstName);
strcat(name, lastName);
printf("%s\n", name);
return 0;
}
2. 使用sprintf进行字符串拼接
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *firstName = "Theo";
char *lastName = "Tsao";
char *name = (char *) malloc(strlen(firstName) + strlen(lastName));
sprintf(name, "%s%s", firstName, lastName);
printf("%s\n", name);
return 0;
}
转载出处:https://www.cnblogs.com/cocoajin/p/4303582.html
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char *join1(char *, char*);
void join2(char *, char *);
char *join3(char *, char*);
int main(void) {
char a[4] = "abc"; // char *a = "abc"
char b[4] = "def"; // char *b = "def"
char *c = join3(a, b);
printf("Concatenated String is %s\n", c);
free(c);
c = NULL;
join2(a,b);
printf("a is %s \n",a);
return 0;
}
/*方法一,不改变字符串a,b, 通过malloc,生成第三个字符串c, 返回局部指针变量*/
char *join1(char *a, char *b) {
char *c = (char *) malloc(strlen(a) + strlen(b) + 1); //局部变量,用malloc申请内存
if (c == NULL) exit (1);
char *tempc = c; //把首地址存下来
while (*a != '\0') {
*c++ = *a++;
}
while ((*c++ = *b++) != '\0') {
;
}
//注意,此时指针c已经指向拼接之后的字符串的结尾'\0' !
return tempc;//返回值是局部malloc申请的指针变量,需在函数调用结束后free之
}
/*方法二,直接改掉字符串a,*/
void join2(char *a, char *b) {
//注意,如果在main函数里a,b定义的是字符串常量(如下):
//char *a = "abc";
//char *b = "def";
//那么join2是行不通的。
//必须这样定义:
//char a[4] = "abc";
//char b[4] = "def";
while (*a != '\0') {
a++;
}
while ((*a++ = *b++) != '\0') {
;
}
}
/*方法三,调用C库函数,*/
char* join3(char *s1, char *s2)
{
char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
//in real code you would check for errors in malloc here
if (result == NULL) exit (1);
strcpy(result, s1);
strcat(result, s2);
return result;
}
转载出处:https://blog.csdn.net/dl15600383645/article/details/46990985
1.字符串的拷贝
//字符串的拷贝
void stringCopy(char *str1, char *str2)
{
while (*str1 != '\0') {
*str2 = *str1;
str1++;
str2++;
}
}