cin读取空格前字符串
# include<iostream>
using namespace std;
int main()
{
char a[20];
cin >> a;
cout << "输入的是:" << a << endl;
cout << "sizeof(a):" << sizeof(a) << endl;
return 0;
}
aaa 111
输入的是:aaa
sizeof(a):20
总结:读到空格便结束
以\0结尾
# include<iostream>
using namespace std;
int main()
{
char a[20];
cin >> a;
cout << "输入的是:";
for(int i = 0; a[i] != '\0'; i++){
cout << a[i];
}
cout << endl;
return 0;
}
sad 222
输入的是:sad
cin.get()读取一行
# include<iostream>
using namespace std;
int main()
{
char a[20];
cin.get(a, 20);
cout << "输入的是:" << a << endl;
return 0;
}
aaa 111
输入的是:aaa 111
# include<iostream>
using namespace std;
int main()
{
char a[]={'a', 32, 'b', 65, ' ', 'B', '\0'};
cout << a << endl;
cout << "sizeof(a):" << sizeof(a) << endl;
return 0;
}
a bA B
sizeof(a):7
sizeof()和strlen()
# include<iostream>
using namespace std;
#include<bits/stdc++.h>
int main()
{
char a[12] = {"Hello World"};
cout << "a:" << a << endl;
cout << "strlen(a):" << strlen(a) << endl;
cout << "sizeof(a):" << sizeof(a) << endl << endl;
a[5]='\0';
cout << "a:" << a << endl;
cout << "strlen(a):" << strlen(a) << endl;
cout << "sizeof(a):" << sizeof(a) << endl;
return 0;
}
a:Hello World
strlen(a):11
sizeof(a):12
a:Hello
strlen(a):5
sizeof(a):12
总结:
- strlen 输出的是可见字符的长度,遇到’\0’就结束了;
- sizeof 输出的是所有字符的长度,’\0’不结束,也算作是一个字符;
strcat()和strncat():字符串的合并
strcat():将ch2全部合并到ch1上
#include<iostream>
using namespace std;
#include<string.h>
int main()
{
char ch1[50] = {"What is your name?"};
char ch2[] = {"My name is Mike!"};
strcat(ch1, ch2);
cout << "ch1:" << ch1 << endl;
cout << "ch2:" << ch2 << endl;
return 0;
}
ch1:What is your name?My name is Mike!
ch2:My name is Mike!
strncat():将ch2的部分合并到ch1上
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char ch1[10] = {"12"};
char ch2[] = {"abcdef"};
strncat(ch1, ch2, 3);
cout << "ch1:" << ch1 << endl;
cout << "ch2:" << ch2 << endl;
return 0;
}
ch1:12abc
ch2:abcdef
strcpy()和strncpy():字符串拷贝
strcpy():将ch2拷贝到ch1上,抹去ch1原来的数据
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char ch1[10] = {"11222222"};
char ch2[] = {"abcdef"};
strcpy(ch1, ch2);
cout << "ch1:" << ch1 << endl;
cout << "ch2:" << ch2 << endl;
return 0;
}
ch1:abcdef
ch2:abcdef
strncpy()
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char ch1[10] = {"11222222"};
char ch2[] = {"abcdef"};
strncpy(ch1, ch2, 5);
cout << "ch1:" << ch1 << endl;
cout << "ch2:" << ch2 << endl;
return 0;
}
ch1:abcde222
ch2:abcdef
memmove():字符串拷贝
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char ch1[15] = {"abcdefghijklmn"};
char ch2[] = {"1234567890"};
cout<<"原ch1字符串:"<<ch1<<endl;
memmove(ch1, ch2, 10);
cout << "拷贝后ch1:" << ch1 << endl;
return 0;
}
原ch1字符串:abcdefghijklmn
拷贝后ch1:1234567890klmn
参考博客
C++char型字符串:https://blog.csdn.net/CYKsky/article/details/42065385 C语言的字符串的操作函数:https://blog.csdn.net/wuyuzun/article/details/82117136 https://blog.csdn.net/weixin_46562430/article/details/120385042
|