string相关函数


头文件#include <cctype>

 

输出包含的标点符号

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

int main()
{
    std::string s1 = "lolita is a beautiful girl ? yes !";

    //输出其中的标点符号
    for(auto c : s1)
        if(ispunct(c))
            std::cout<<c<<std::endl;
    return 0;
}

将所有小写转换为大写字母

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

int main()
{
    std::string s1 = "lolita is a beautiful girl ? yes !";

    for(auto &c : s1)
        if(islower(c))
            c = toupper(c);

    std::cout<<s1<<std::endl;
    return 0;
}

 

将首个单词大写

 

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

int main()
{
    std::string s1 = "lolita is a beautiful girl ? yes !";

    for(decltype(s1.size()) index = 0 ;
    index<s1.size()&&!isspace(s1[index]);
    index++)
    {
        s1[index] = toupper(s1[index]);
    }

    std::cout<<s1<<std::endl;
    return 0;
}

 

 

判断首字母大小写

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

int main()
{
    std::string s1 = "lolita is a beautiful girl ? yes !";

    if(s1.size()>0) //很重要
    {
        if(isupper(s1[0]))
        {
            std::cout<<"首字母大写"<<std::endl;
        }
        else
        {
            std::cout<<"首字母小写"<<std::endl;
        }
    }
    else
    {
        std::cout<<"空字符串"<<std::endl;
    }

    return 0;
}

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM