总结——字符串、字符串数组、文件读写

一 字符串 <string>

  创建 string a;

  赋值 a=temp; //string中的“ = ”就以代表开辟内存空间,不代表地址赋值。不用考虑指针的问题。

  长度 a.length()

  比较 a.compare(temp); //相等,return 0;大于,return 大于0的值;小于,return 小于的值。

  子串 a.substr(0,1);//从 str[2][0]截取长度为1的子串

  插入 a.insert(int p0, int n, char c);//此函数在下标p0处插入n个字符c

  转换 char* printf("%s",s.c_str());

  输入 scanf(C)不能对类进行读入,所以不能使用scanf读入,只能使用cin

  输出 可以使用printf("%s",s.c_str()),但不建议。推荐使用cout。 

 

二 字符串数组 <string>

  创建 string str[100];

  长度 str[0].length();

  排序 

#include<algorithm>  
#include<cstring>  
#include<cstdio>  
#include<iostream>  
using namespace std;  
string str[1005];  

int cmp(string a,string b)  {  
    return a.compare(b)<0;  
}  
int main()  
{  
    int n;  
    scanf("%d", &n);  
    for (int i=0; i<n; i++)  
        cin>>str[i];  
    sort(str, str+n, cmp);  
    return 0;  
}
字符串数组排序
#include<algorithm>  
#include<cstring>  
#include<cstdio> 

#define M  100000  
#define len 22  
using namespace std;

char str[M][len];
int cmp1(const void *a, const void*b) {
    char *s1 = (char *)a;
    char *s2 = (char *)b;
    return strcmp(s1, s2);
}
int main()
{
    int n;
    scanf("%d", &n);
    for (int i = 0;i<n;i++)
        scanf("%s", str[i]);
    qsort(str, n, sizeof(char)*len, cmp1);
    for (int i = 0;i < n;i++)
        printf("%s\n", str[i]);
        return 0;
}
二维字符数组排序

 

三 char* 与 string

  1. 转换

  char[] -> string: sring s(s1); 或“=”直接赋值 s=s1; 

  string -> char[]: c_str() //c_str()返回const *char 类型的不可更改的临时指针,建议输出直接printf("%s",s.c_str());

 

  2. 头文件:使用<cstdio>库代替<stdio.h>,注意加 using namespace std; (①<cstdio>是C++定义的库,调用后者的函数;②".h"头文件将所有名字放在global namespace中,在新的方式下(指的是诸如cstdio这样的头文件),名字是放在namespace std中的。

  char* 输入:scanf() gets() getchar() /*gets() 在头文件<string>中定义,scanf()空格终止,gets()回车终止*/

  char* 输出:printf()

  string :cin / cout

 

 

四 其他细节

  1.文件读写  //头文件<cstdio><stdio.h>,统一<cstdio>

    freopen("Input.txt","r",stdin);  

    freopen("Output.txt","w",stdout); 

 

  2.循环中止

    while(scanf("%d",a)!=EOF){...}

 

  3.scanf("\n");

    scanf() 在输入时尽量不要用'\n',表示的不是读入回车,而是清空缓冲区,当需要读入回车,否则会影响到下一个char类型时(int类型读入时会忽略数字前面的空格、回车),单独写一句scanf("\n");

 

  4.scanf(" %c",&cvar);

    char类型的读入不会忽略前面的空格,必要的空格不能省略。

 

转载于:https://www.cnblogs.com/travelller/p/8318498.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值