毕业编程汇总5——各种字符串问题

1. 回文字符串 

reverse 函数实现的是字符串的原地反转

#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
int main()
{
    string s;
    while(cin>>s)
    {
        string a = s;
        reverse(s.begin(),s.end());
        if(s==a)
            cout<<"Yes!"<<endl;
        else 
            cout<<"No!"<<endl;
        
    }
}

2. 不借用任何字符串库函数实现无冗余地接受两个字符串,然后把它们无冗余的连接起来。

如果是输入一串字符串并保存到字符数组中,系统会自动在后面补\0,无需自己输入。

#include <iostream>
using namespace std;
int main()
{
    char a[101];
    char b[101]; //字符数组,最后通常为\0,以表征字符串的结束
    while(cin>>a>>b)
    {
        char res[201];
        char *p=a;  //指向字符数组的指针,直接赋值即可
        int i=0;
        while(*p!='\0')
        {
            res[i]=*p;
            p++;
            i++;
        }
        char *q=b;
        while(*q!='\0')
        {
            res[i]=*q;
            q++;
            i++;
        }
        res[i]='\0';
        cout<<res<<endl;
    }
    return 0;
}

3. C中也有一系列处理字符串的函数,在cstring头文件中,字符串处理缓存有:字符串拼接函数strcat(string 1,string 2)将字符串2接到字符串1的后面,字符串1的\0结束标志被删除;字符串拷贝strcpy(string 1, string 2)将字符串2复制到字符串1中;字符串比较函数strcmp(string 1,string 2),比较字符串大小关系;字符串长度函数strlen(s)。

4. 字符串内排序

#include<iostream>
#include<algorithm>
using namespace std;
bool cmp(char a, char b)
{
    return a<b;
}
int main()
{
    string s;
    while(cin>>s)
    {
        sort(s.begin(),s.end(),cmp); // C++中的快速排序,可以直接调用,可以利用cmp实现多种功能
        cout<<s<<endl; 
    }
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值