字符串 c++

本文介绍了C++中字符串的相关操作,包括输入输出、常用函数如strlen、strcmp、strcpy,以及标准库类型`std::string`的特点,强调了`string`的`empty`、`size`方法的使用,并指出其size返回的是无符号整数。

字符串

输入输出

  • 字符串等于字符数组加结束符’\0’,所以字符数组长度要加一
char a1[] = {'c','+','+'};            //列表初始化无空字符

char a2[] = {'c','+','+','\0'};       //含有显示的空字符

char a3[] = {"c++"};             //自动添加结尾空字符

char a4[6] =" Daniel";       //错误!没有空间存放空字符'\0'
  • cin 与 scanf 在读入到 " " 或 ‘\0’ 或 “\n” 时会结束

  • 要读入整行字符时需要fgets(s,100,stdin);或 getline(s,100);

  • 让字符数组从第n 项输出: a[] +x;

常用操作

  • #include <string.h> 包含:

  • (1)strlen(str) 求字符串长度

  • (2)strcmp(a,b) 比较两个字符串的大小(字典序), a < b 返回-1,a == b返回0,a > b 返回1

  • (3) strcpy(a,b) 将字符串b复制给从a开始的字符数组

  • 遍历 : 当成数组

    #include <cstdio>
    #include <iostream>
    #include <cstring>
    
    using namespace std;
    int main ()
    {
    	char s1[100],s2[100];
    	
    	scanf("%s",s1);
    	
    	for (int i =0 ; i < strlen (s1); i++) cout << s1[i] << endl;
    	
    	return 0;
    }
    

标准库类型 string

  • 可变长的字符序列,比字符数组更好用,需要引入: #include
#include <cstdio>
#include <iostream>
#include <cstring>

using namespace std;
int main ()
{
	string s1;       // 默认的空字符串
	string s2 = s1;  //  s2是s1的一个副本
	string s3 = "hiya"   // s3是该字符串字面值的一个副本 
	string s4 (10,'c');   //定义10个c 
	
	return 0; 
}

string 的empty 和 size和相加操作 (注意size 是无符号整数,因此s.size() <= -1 一定成立

  • empty >> 空返回 1 否则返回 0
#include <cstdio>
#include <iostream>
#include <cstring>

using namespace std;
int main ()
{
	string s1 = "abc",s2;
	
	cout << s1.empty()  << endl;
	cout << s2.empty()  << endl;
	 
	return 0; 
}
  • size 长度

    #include <cstdio>
    #include <iostream>
    #include <cstring>
    
    using namespace std;
    int main ()
    {
    	string s1 = "abc",s2;
    	
    	cout << s1.size() << endl;
    	cout << s2.size() << endl;
    	
    	return 0; 
    }
    
    • 相加

      #include <cstdio>
      #include <iostream>
      #include <cstring>
      
      using namespace std;
      int main ()
      {
      	string s1 = "abc",s2 = "def";
      	
      	string s3 = s1+s2;
      	
      	cout << s3;   //输出abcdef 
      	return 0; 
      }
      

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值