C++学习笔记-string-2

本文详细介绍了C++中字符串的基本操作,包括获取字符串大小、判断字符串是否为空以及遍历字符串。同时,深入探讨了如何使用标准库函数检查字符属性,如判断字符是否为标点符号、字母或数字,并提供了去除字符串中所有标点符号的示例代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.

#include<iostream>
#include<string>
#include<cctype>//加了一个c,把.h去掉,把c语言的头文件换成c++的文件,标准库函数都是一样的

using namespace std;

int main()
{
    string s("hello world");//string类型不是字符数租,还是可以用下标操作字符,比较灵活
    //用一个变量接收字符串的大小

    string::size_type size = s.size();//size_type专门用来保存字符串的大小的

    cout << size << endl;
    //判断字符串是不是空的,判断大小就行  s.size==0
    //s.empty()判断字符串是不是空的
    cout << s[1] << endl;
    cout << s[2] << endl; 

    for (string::size_type x = 0;x != s.size(); ++x)//for循环输出
    {
        cout << s[x];
    }
    cout << endl;


    system("pause");
    return 0;//一般用在主函数结束时,按照程序开发的一般惯例,表示成功完成本函数
    //endl运算符打印,这是一个被称为操作符的特殊值,写入endl的效果是结束当前行,并将与设备关联的缓冲区的内容刷到设备中。缓冲刷新操作可以保证是
    //到目前为止程序产生的所有输出都是真正写入到输出流中,而不是仅停留在内存中等待写入流
}

2.续

#include<iostream>
#include<string>
#include<cctype>

using namespace std;//c语言学过的东西在c++照常使用

int main()
{


    string s1("HELLO bill!!!");

    string::size_type punct_cnt = 0;//保存标点符号的个数

    for (string::size_type index = 0; index != s1.size(); ++index)
    {
        if (ispunct(s1[index]))
            ++punct_cnt;
    }
    //isalnum(c)c是字母或者数字就是true
    //isalpha 是不是字母
    //islower是不是小写字母
    //issapce是不是空格
    //for (string::size_type index = 0; index != s1.size(); ++index)
    //{
    //  s1[index] = tolower(s1[index]);
    //}
    //for (string::size_type index = 0; index != s1.size(); ++index)
    //{
    //  cout << s1[index];
    //}
    //cout << endl;
    ////for循环输出改变的字符串
    //cout << s1 << endl;//直接输出
    //cout << punct_cnt << endl;

    //习题
    string s2, pr;
    char ch;
    bool has_punct=false;
    cout << "enter a string" << endl;

    getline(cin, s2);
    for (string::size_type index = 0; index != s2.size(); ++index)//检查输入的字符串的每一个字符
    {
        ch = s2[index];//之后检查是不是标点符号
        if (ispunct(ch))//如果是标点符号
            has_punct = true;//true
        else//有标点符号
        {
            pr += ch;
        }
    }
    if (has_punct)
        cout << pr << endl;
    else
        cout << "no sign" << endl;

    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值