C++相关闲碎记录(15)

news2024/9/23 11:21:34

1、string字符串

#include <iostream>
#include <string>
using namespace std;

int main (int argc, char** argv)
{
   const string delims(" \t,.;");
   string line;

   // for every line read successfully
   while (getline(cin,line)) {
       string::size_type begIdx, endIdx;

       // search beginning of the first word
       begIdx = line.find_first_not_of(delims);

       // while beginning of a word found
       while (begIdx != string::npos) {
           // search end of the actual word
           endIdx = line.find_first_of (delims, begIdx);
           if (endIdx == string::npos) {
               // end of word is end of line
               endIdx = line.length();
           }

           // print characters in reverse order
           for (int i=endIdx-1; i>=static_cast<int>(begIdx); --i) {
               cout << line[i];
           }
           cout << ' ';

           // search beginning of the next word
           begIdx = line.find_first_not_of (delims, endIdx);
       }
       cout << endl;
   }
}
输入:ajsdk12345e.asfa        \jkawefa
输出:e54321kdsja afsa afewakj\ 
(1)string各项操作

 (2)构造函数和析构函数

 data() 和 c_str()以字符数组的形式返回string内容,并且在该数组位置[size()]上有一个'\0'结束字符。copy()将string内容复制到调用者提供的字符数组中,其末尾不添加'\0'字符,注意,data()和c_str()返回的字符数组由该string拥有,也就是说,调用者不可以改动它或者释放其内存。

例如:

std::string s("12345");
atoi(s.c_str())           
f(s.data, s.length())

char buffer[100];
s.copy(buffer, 100);    //copy at most 100 characters os s into buffer
s.copy(buffer, 200, 2); //copy at most 100 characters of s into buffer
                        //starting with the third character of s

一般而言,整个程序你应该坚持使用string,直到你必须将其内容转化为char*时,注意c_str()和data()的返回值的有效期在下一次调用non-const 成员函数时即告终止。

std::string s;
...
foo(s.c_str());  //s.c_str() is valid during the whole statement

const char* p;
p = s.c_str();   //p refers to the contents of s as a C-string
foo(p);          //OK (p is still valid)
s += "ext";      //invalidates p
foo(p);          //ERROR: argument p is not valid
(3)赋值操作
const std::string aString("othello");
std::string s;
s = aString;
s = "two\nlines";
a = ' ';
s.assign(aString);
s.assign(aString, 1, 3);
s.assign(aString, 2, std::string::npos);
s.assign("two\nlines");
s.assign("nico", 5);
s.assign(5, 'x');
(4)安插和移除字符
const std::string aString("othello");
std::string s;
s += aString;
s += "two\nlines";
s += '\n';
s += {'o', 'k'};
s.append(aString);
s.append(aString, 1, 3);   //append "the"
s.append(aString, 2, std::string::npos);    // append "hello"
s.append("two\nlines");
s.append("nico", 5);         //append character array 'n' 'i' 'c' '0' '\0'
s.append(5, 'x');            //append five characters 'x' 'x' 'x' 'x' 'x'
s.push_back('\n');       

s.insert(1, aString);
//注意,成员函数insert()不接受索引+单字符的实参组合,必须传入一个string或者加上一个额外数字
s.insert(0, ' ');  //ERROR
s.insert(0, " ");  //OK
//你也可以这样尝试
s.insert(0, 1,' ');   // ERROR : ambiguous
// 由于insert()具有以下重载形式,上一行会导致令人厌烦的歧义
insert(size_type idx, size_type num, charT c);  //position is index
insert(iterator pos, size_type num, charT c);   //position is iterator
string的size_type通常被定义为unsigned,string的iterator通常被定义为char*。
于是第一实参0有两种转换可能,不分优劣,为了获得正确的操作,必须使用如下:
s.insert((std::string::size_tpye)0, 1, ' ');  //OK
std::string s = "i18n";                 //s:i18n
s.replace(1, 2, "nternationalizatio");  //s:internationalization
s.erase(13);                            //s:international
s.erase(7, 5);                          //s:internal
s.pop_back();                           //s:interna(since C++11)
s.replace(0, 2, "ex");                  //s:externa
(5)子字符串和字符串拼接
std::string s("interchangeability");
s.substr()                  //returns a copy of s
s.substr(11)                //returns string("ability")
s.substr(5, 6);             //returns string("change")
s.substr(s.find('c'));      //returns string("changeability")
(6)getline()

读取一行字符,包括前导空白字符,遇到换行或者end-of-file,分行符会被读取出来,但是不会添加到结果上,默认分行符是换行符号,也可以自定义任意符号作为分行符。

while(std::getline(std::cin,s)) {}
while(std::getline(std::cin, s, ':')){}

 如果自定义了分行符,则换行符就被当做普通字符。

(7)搜索查找

std::string s("Hi Bill, I'm ill, so please pay the bill");
s.find("il");                    //returns 4
s.find("il", 10);                //returns 13
s.rfind("il");                   //returns 37
s.find_first_of("il");           //returns 1
s.find_last_of("il");            //returns 39
s.find_first_not_of("il");       //returns 0
s.find_last_not_of("il");        //returns 36
s.find("hi");                    //returns npos
(8)npos的意义

如果查找失败,会返回string::npos,使用string的npos值及其类型时要格外小心,若要检查函数返回值,一定要使用类型string::size_type,不能使用int或unsigned作为返回值类型,否则返回值与string::npos之间的比较可能无法正确执行,这是因为npos被设置为-1。

事实上(unsigned long)-1与(unsigned short)-1不同,因此对于下列表达式:

idx == std::string::npos,如果idx的值为-1,由于idx和string::npos类型不同,比较结果可能会是false。

(9)数值转换

自C++11起,C++标准库提供了一些便捷函数,用来将string转换为数值或者反向转换,但是只适用于类型string或者wstring类型,不适用于u16string和u32string。

#include <string>
#include <iostream>
#include <limits>
#include <exception>

int main()
{
  try {
    // convert to numeric type
    std::cout << std::stoi ("  77") << std::endl;
    std::cout << std::stod ("  77.7") << std::endl;
    std::cout << std::stoi ("-0x77") << std::endl;

    // use index of characters not processed
    std::size_t idx;
    std::cout << std::stoi ("  42 is the truth", &idx) << std::endl;
    std::cout << " idx of first unprocessed char: " << idx << std::endl;

    // use bases 16 and 8
    std::cout << std::stoi ("  42", nullptr, 16) << std::endl;
    std::cout << std::stol ("789", &idx, 8) << std::endl;
    std::cout << " idx of first unprocessed char: " << idx << std::endl;

    // convert numeric value to string
    long long ll = std::numeric_limits<long long>::max();
    std::string s = std::to_string(ll);  // converts maximum long long to string
    std::cout << s << std::endl;

    // try to convert back
    std::cout << std::stoi(s) << std::endl;  // throws out_of_range
  }
  catch (const std::exception& e) {
    std::cout << e.what() << std::endl;
  }
}
输出:
77
77.7
0
42
 idx of first unprocessed char: 4
66
7
 idx of first unprocessed char: 1
9223372036854775807
stoi

 std::stoi("-0x77")只会解析-0,std::stol("789", &idx, 8)只解析7,因为8在8进制中是一个无效字符。

(10)string iterator使用实例

#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>
#include <regex>
using namespace std;


int main()
{
    // create a string
    string s("The zip code of Braunschweig in Germany is 38100");
    cout << "original: " << s << endl;

    // lowercase all characters
    transform (s.cbegin(), s.cend(),  // source
               s.begin(),             // destination
               [] (char c) {          // operation
                   return tolower(c);
               });
    cout << "lowered:  " << s << endl;

    // uppercase all characters
    transform (s.cbegin(), s.cend(),  // source
               s.begin(),             // destination
               [] (char c) {          // operation
                   return toupper(c);
               });
    cout << "uppered:  " << s << endl;

    // search case-insensitive for Germany
    string g("Germany");
    string::const_iterator pos;
    pos = search (s.cbegin(),s.cend(),     // source string in which to search
                  g.cbegin(),g.cend(),     // substring to search
                  [] (char c1, char c2) {  // comparison criterion
                      return toupper(c1) == toupper(c2);
                 });
    if (pos != s.cend()) {
        cout << "substring \"" << g << "\" found at index "
             << pos - s.cbegin() << endl;
    }
}
输出:
original: The zip code of Braunschweig in Germany is 38100
lowered:  the zip code of braunschweig in germany is 38100
uppered:  THE ZIP CODE OF BRAUNSCHWEIG IN GERMANY IS 38100
substring "Germany" found at index 32
(11)为string打造trait class,允许以大小写无关的方式操作字符
#ifndef ICSTRING_HPP
#define ICSTRING_HPP

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

// replace functions of the standard char_traits<char>
// so that strings behave in a case-insensitive way
struct ignorecase_traits : public std::char_traits<char> {
    // return whether c1 and c2 are equal
    static bool eq(const char& c1, const char& c2) {
        return std::toupper(c1)==std::toupper(c2);
    }
    // return whether c1 is less than c2
    static bool lt(const char& c1, const char& c2) {
        return std::toupper(c1)<std::toupper(c2);
    }
    // compare up to n characters of s1 and s2
    static int compare(const char* s1, const char* s2,
                       std::size_t n) {
        for (std::size_t i=0; i<n; ++i) {
            if (!eq(s1[i],s2[i])) {
                return lt(s1[i],s2[i])?-1:1;
            }
        }
        return 0;
    }
    // search c in s
    static const char* find(const char* s, std::size_t n,
                            const char& c) {
        for (std::size_t i=0; i<n; ++i) {
            if (eq(s[i],c)) {
                return &(s[i]);
            }
        }
        return 0;
    }
};

// define a special type for such strings
typedef std::basic_string<char,ignorecase_traits> icstring;

// define an output operator
// because the traits type is different from that for std::ostream
inline
std::ostream& operator << (std::ostream& strm, const icstring& s)
{
    // simply convert the icstring into a normal string
    return strm << std::string(s.data(),s.length());
}

#endif    // ICSTRING_HPP
#include "icstring.hpp"

int main()
{
    using std::cout;
    using std::endl;

    icstring s1("hallo");
    icstring s2("otto");
    icstring s3("hALLo");
    
    cout << std::boolalpha;
    cout << s1 << " == " << s2 << " : " << (s1==s2) << endl;
    cout << s1 << " == " << s3 << " : " << (s1==s3) << endl;

    icstring::size_type idx = s1.find("All");
    if (idx != icstring::npos) {
        cout << "index of \"All\" in \"" << s1 << "\": "
             << idx << endl;
    }
    else {
        cout << "\"All\" not found in \"" << s1 << endl;
    }
}
输出:
hallo == otto : false
hallo == hALLo : true
index of "All" in "hallo": 1

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1315860.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

布局前沿技术,紫光展锐推动6G创新融合发展

随着5G进入规模化商用阶段&#xff0c;6G研究已在全球范围内拉开帷幕。2023年6月&#xff0c;ITU发布了《IMT面向2030及未来发展的框架和总体目标建议书》&#xff0c;在升级5G三大应用场景的同时&#xff0c;扩展出三个跨领域场景&#xff0c;形成6G的六大应用场景&#xff0c…

读书心得(内容取自高质量C/C++编程)

版式虽然不会影响程序的功能&#xff0c;但会影响可读性。程序的版式追求清晰、美观&#xff0c;是 程序风格的重要构成因素。 可以把程序的版式比喻为“书法”。好的“书法”可让人对程序一目了然&#xff0c;看得兴致勃勃。差的程序“书法”如螃蟹爬行&#xff0c;让人看得…

C++实现简单的猜数字小游戏

猜数字 小游戏介绍&#xff1a;猜数字游戏是令游戏机随机产生一个100以内的正整数&#xff0c;用户输入一个数对其进行猜测&#xff0c;需要你编写程序自动对其与随机产生的被猜数进行比较&#xff0c;并提示大了&#xff0c;还是小了&#xff0c;相等表示猜到了。如果猜到&…

音频DAC,ADC,CODEC的选型分析,高性能立体声

想要让模拟信号和数字信号顺利“交往”&#xff0c;就需要一座像“鹊桥”一样的中介&#xff0c;将两种不同的语言转变成统一的语言&#xff0c;消除无语言障碍。这座鹊桥就是转换器芯片&#xff0c;也就是ADC芯片。ADC芯片的全称是Analog-to-Digital Converter, 即模拟数字转换…

TCPIP介绍

可见 TCP/IP 被分为 4 层&#xff0c;每层承担的任务不一样&#xff0c;各层的协议的工作方式也不一样&#xff0c;每层封装上层数据的方式也不一样&#xff1a; 应用层&#xff1a;应用程序通过这一层访问网络&#xff0c;常见 FTP、HTTP、DNS 和 TELNET 协议&#xff1b; 传输…

【C语言】详解文件操作

&#xff08;零&#xff09;引入 终端是计算机系统中与用户进行交互的界面。 在以往的程序中&#xff0c;我们通过终端用键盘输入数据&#xff0c;通过屏幕输出信息。 但是&#xff0c;如果我们不想手动低效地输入数据&#xff0c;而是通过文件一次性高效输入&#xff1b; 如果…

OpenHarmony 如何去除系统锁屏应用

前言 OpenHarmony源码版本&#xff1a;4.0release / 3.2 release 开发板&#xff1a;DAYU / rk3568 一、3.2版本去除锁屏应用 在源码根目录下&#xff1a;productdefine/common/inherit/rich.json 中删除screenlock_mgr组件的编译配置&#xff0c;在rich.json文件中搜索th…

GraphicsProfiler 使用教程

GraphicsProfiler 使用教程 1.工具简介&#xff1a;2.Navigation介绍2.1.打开安装好的Graphics Profiler。2.2.将手机连接到计算机&#xff0c;软件会在手机中安装一个GraphicsProfiler应用(该应用是无界面的&#xff09;。2.3.Show files list2.4.Record new trace2.4.1.Appli…

自然数分解 C语言xdoj64

输入说明 一个正整数 n&#xff0c;0<n<30 输出说明 输出n个连续奇数&#xff0c;数据之间用空格隔开&#xff0c;并换行 输入样例 4 输出样例 13 15 17 19 int main() {int n;scanf("%d",&n);if(n % 2 0){//n为偶数int in;//打印数字个数&#xff0c;做循…

【每日一题】统计区间中的整数数目

文章目录 Tag题目来源解题思路方法一&#xff1a;平衡二叉搜索树 写在最后 Tag 【平衡二叉搜索树】【设计类】【2023-12-16】 题目来源 2276. 统计区间中的整数数目 解题思路 方法一&#xff1a;平衡二叉搜索树 思路 用一棵平衡二叉搜索树维护插入的区间&#xff0c;树中的…

Java-----链表练习题(上)

本篇碎碎念&#xff1a;本篇无碎碎念 今日份励志文案: 很多人认为他们在思考&#xff0c;其实他们只是在整理自己的偏见 目录 一.203. 移除链表元素 - 力扣&#xff08;LeetCode&#xff09; 二.21. 合并两个有序链表 - 力扣&#xff08;LeetCode&#xff09…

【STM32入门】4.2对射红外传感器计次

1.接线方式 主要是编写传感器的驱动、配合OLED&#xff0c;每遮挡对射红外传感器&#xff0c;OLED屏幕的计数就加一。 2.驱动编写 首先新建.c文件和.h文件&#xff0c;命名为CountSensor 国际惯例&#xff0c;.c文件内要包含stm32.h头文件&#xff0c;然后编写 CountSensor_…

C++初阶-list类的模拟实现

list类的模拟实现 一、基本框架1.1 节点类1.2 迭代器类1.3 list类 二、构造函数和析构函数2.1 构造函数2.2 析构函数 三、operator的重载和拷贝构造3.1 operator的重载3.2 拷贝构造 四、迭代器的实现4.1 迭代器类中的各种操作4.1 list类中的迭代器 五、list的增容和删除5.1 尾插…

力扣第2题-判断一个数值是否是回文数[简单]

题目描述 给你一个整数 x &#xff0c;如果 x 是一个回文整数&#xff0c;返回 true &#xff1b;否则&#xff0c;返回 false 。 回文数是指正序&#xff08;从左向右&#xff09;和倒序&#xff08;从右向左&#xff09;读都是一样的整数。 例如&#xff0c;121 是回文&am…

c语言中的static静态(1)static修饰局部变量

#include<stdio.h> void test() {static int i 1;i;printf("%d ", i); } int main() {int j 0;while (j < 5){test();j j 1;}return 0; } 在上面的代码中&#xff0c;static修饰局部变量。 当用static定义一个局部变量后&#xff0c;这时局部变量就是…

蓝桥杯专题-真题版含答案-【扑克牌排列】【放麦子】【纵横放火柴游戏】【顺时针螺旋填入】

Unity3D特效百例案例项目实战源码Android-Unity实战问题汇总游戏脚本-辅助自动化Android控件全解手册再战Android系列Scratch编程案例软考全系列Unity3D学习专栏蓝桥系列ChatGPT和AIGC &#x1f449;关于作者 专注于Android/Unity和各种游戏开发技巧&#xff0c;以及各种资源分…

人工智能与量子计算:开启未知领域的智慧之旅

导言 人工智能与量子计算的结合是科技领域的一场创新盛宴&#xff0c;引领我们进入了探索未知领域的新时代。本文将深入研究人工智能与量子计算的交汇点&#xff0c;探讨其原理、应用以及对计算领域的深远影响。 量子计算的崛起为人工智能领域注入了新的活力&#xff0c;开启了…

认知能力测验,①如何破解数字推理类测试题?

校园招聘&#xff08;秋招春招&#xff09;&#xff0c;最为常见的认知能力测验&#xff0c;在线工具网将整理分析关于认知能力测验的系列文章&#xff0c;希望能帮助大家顺利通过认知能力测评&#xff0c;找到自己心仪的工作。 数字推理测试&#xff0c;是我们在求职中经常会…

汇编语言的前世今生

计算机中的0和1是用电的状态表示的。具体来说&#xff0c;断开为0&#xff0c;接通为1。自然而言&#xff0c;这也对应着二进制。曾经时代的二进制加法机是一个划时代的产物&#xff0c;能够进行两个8位二进制数的实时加法&#xff0c;尽管今天看来很LOW。 图1 二进制加法器&am…

面向对象三大特征之二:继承

继承的快速入门 什么是继承&#xff1f; Java中提供了一个关键字extends&#xff0c;用这个关键字&#xff0c;可以让一个类与另一个类建立起父子关系 继承的特点 子类能继承父类的非私有成员&#xff08;成员变量、成员方法&#xff09; 继承后对象的创建 子类的对象是由…