C++ 字符串 *** 作

C++ 字符串 *** 作,第1张

文章目录
  • 1.1 C++ 字符串 *** 作
    • 2.2字符数组的常用 *** 作
    • 2.3遍历字符数组的字符
    • 3.标准库类型string
      • 3.1 定义和初始化
      • 3.2 string的 *** 作
        • 1)读写 *** 作
        • 2)使用`getline`读取一整行
        • 3)string的方法 *** 作
        • 4)字符串和string相加
      • 3.3处理string对象中的字符

1.1 C++ 字符串 *** 作 2.2字符数组的常用 *** 作

下面几个函数需要额外引入头文件:

#include 
  1. strlen(str),求字符串的长度
  2. strcmp(a, b),比较两个字符串的大小,a < b返回-1,a == b返回0,a > b返回1。这里的比较方式是字典序!
  3. strcpy(a, b),将字符串b复制给从a开始的字符数组。
#include 
#include 

using namespace std;

int main()
{
    char a[100] = "hello world!", b[100];

    cout << strlen(a) << endl;

    strcpy(b, a);

    cout << strcmp(a, b) << endl;

    return 0;
}
2.3遍历字符数组的字符
#include 
#include 

using namespace std;

int main()
{
	char a[100] = "what fk";
	int len = strlen(a);
	for (int i = 0; i < len; i++)
		cout << a[i] << endl;

	return 0;
}
3.标准库类型string

是C++标准库头文件,包含了拟容器class std::string的声明

另外补充

1.是C标准库头文件的C++标准库版本, 包含了C风格字符串(NUL即’\0’结尾字符串)相关的一些类型和函数的声明,例如strcmp、strchr、strstr等。

2.的最大区别在于,其中声明的名称都是位于std命名空间中的,而不是后者的全局命名空间。

3.1 定义和初始化
#include 
#include 

using namespace std;

int main()
{
	string a ;
	string b = a;
	if(a == b) cout << "stan";
	return 0;
}
3.2 string的 *** 作 1)读写 *** 作

注意:不能用printf直接输出string,

需要写成:printf(“%s”, s.c_str());

#include 
#include 

using namespace std;

int main()
{
	
	string s1 , s2;
	cin >> s1 >> s2;
	cout << s1 << s2 << endl;
	printf("%s", s1.c_str());

	return 0;
}
2)使用getline读取一整行
#include 
#include 

using namespace std;

int main()
{
	string s1;
	getline(cin, s1);
	cout << s << endl;

	return 0;
}
3)string的方法 *** 作

size的使用,得到字符长度

⚠注意size是无符号整数,因此 s.size() <= -1一定成立

#include 
#include 

using namespace std;

int main()
{
	string s1 = "abcde";
	int len = s1.size();
	cout << len << endl;

	return 0;
}
4)字符串和string相加
#include 
#include 

using namespace std;

int main()
{
	string s1 = "abcde";
	string s2 = s1 + "efg";
	string s3 = "efg" + s1;
    //会报错:gument domain error (DOMAIN)
	// string s4 = "efg" + 123;
    //表达式必须具有整数或未区分范围的枚举类型
	// string s5 = "asdf" +"asd"
	cout << s2 << endl;
	cout << s3 << endl;
	cout << s4 << endl;
	return 0;
}

🚩也就是说每个加法运算的两侧必须至少有一个string

3.3处理string对象中的字符

可以将string对象当成字符数组来处理:

#include 
#include 

using namespace std;

int main()
{
	string s1 = "one";
	for(int i= 0;i <s1.size();i++)
		cout << s1[i];


	return 0;
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/2990612.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-09-23
下一篇 2022-09-23

发表评论

登录后才能评论

评论列表(0条)

保存