C定义字符串
char数组字符串的最后一个字符都是'\0' ,以表示字符串的结束。实际大小要+1,因为系统自动补'\0' 。可以用作结束的标志:while(s[i]!='\0') 或者 while(*p) sizeof(s) :计算的是数组的总大小 strlen(s) : 仅字符串长度,不包括’\0’
char数组:
char 类型数组,可以不指定大小 char s[]="xxx"; 访问:s[i] 大小:sizeof(s)/strlen(s)
char a[5] = "abcd";
char s[]= "abcd";
int i = 0;
while (s[i] != '\0')
cout << s[i++];
const char指针:
const char* s="xxx"; ,常量字符串,不可更改s的值! 访问:p[i] / *(p++) 大小:sizeof(p) / strlen(p)
const char* p = "abcd";
while (*p)
cout << *(p++);
长度:
char s[5]="abc"
cout << sizeof(s) << endl;
cout << strlen(s) << endl;
结果分别为 5 ,3
char s[]="abc"
cout << sizeof(s) << endl;
cout << strlen(s) << endl;
结果分别为 4,3
C的输入输出
字符串可以直接用其数组名(指针)输入输出。 注:scanf 输入Space/Enter/Tab (空格、回车、tab键)即停止输入。
char s[10];
scanf("%s",s);
printf("%s",s);
while(scanf("%d",&n)!=EOF)
new/malloc动态分配
C: char *p=(char *)malloc(sizeof(char)*Maxsize); C++: char *p=new char[Maxsize]; 1.访问: p[i]/*(p++) 2.长度:可以用sizeof(p) 计算总大小,不可用strlen(p) 3.需要逐一赋值,没有'\0' ,可以自行添加。
C++定义字符串
string类:
string.h 里面有string类,可以直接定义字符串(为类对象) 1.访问:s[i] 2.长度:可以调用length() 函数计算长度 s.length() 。 3.区别于C:没有 '\0'
string str = "abc";
for (int i = 0; i < str.length(); i++)
cout << str[i];
C++输入输出
1.直接cin/cout 输入输出 注:cin 输入Space/Enter/Tab (空格、回车、tab键)即停止输入。
char s[10];
cin>>s;
cout<<s;
while(cin>>n)
输入:qwe rt 输出:qwe
2.cin.get() 注:Enter (回车)即停止输入。可以接受空格。
char s[20];
cin.get(s,20);
输入:qwe rty 输出:qwe rty
多次使用cin.get(s,size) 需要在中间使用一个无参数cin.get()/getchar() 的来消去回车。
char s1[10];
cin.get(s1,10);
cin.get();
cout<<s1<<endl;
cin.get(s1,5);
cout<<s1<<endl;
CSDN的这个markdown编辑,(p)直接变成了什么鬼符号???
|