【C++标准库】字符串

string filename = "test.cpp";
string::size_type idx = filename.find('.');
//size_type是string class定义的一个无正负号整数类型,size_type类型取决于string class的内存模型
//idx不能定义为int或者unsigned类型,否则与string::npos的比较动作无法有效运行
if (idx == string::npos)
{
    cout << "find fail..." << endl;
}

从标准输入设备输入一个个单词,然后字符逆序打印。

/* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference, 2nd Edition"
* by Nicolai M. Josuttis, Addison-Wesley, 2012
*
* (C) Copyright Nicolai M. Josuttis 2012.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#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;
    }
}
View Code

 在<string>中,basic_string<>类被定义为所有string类型的基础模板类,它将字符类型、字符类型的trait、内存模型都参数化了。

C++标准库提供了若干basic_string<>的特化版本:

typedef basic_string<char> string;
typedef basic_string<wchar_t> wstring;
typedef basic_string<char16_t> u16string;
typedef basic_string<char32_t> u32string;

C++ standard中将字符串字面常量的类型由char*改为const char*.有三个函数可以将string内容转换为字符数组或者C-String

  • data()c_str()以字符数组的形式返回string内容,在数组最后有一个结束符,所以其结果是一个内含\0字符的有效C-String
  • copy()将string内容复制到字符数组中,末尾添加'\0'字符

 

转载于:https://www.cnblogs.com/larry-xia/p/9504537.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值