Chinaunix首页 | 论坛 | 博客
  • 博客访问: 119620
  • 博文数量: 29
  • 博客积分: 1215
  • 博客等级: 中尉
  • 技术积分: 305
  • 用 户 组: 普通用户
  • 注册时间: 2010-12-05 16:29
文章分类
文章存档

2010年(29)

我的朋友

分类: C/C++

2010-12-21 22:29:08

本文通过一个程序实例来说明sting类型的相关操作。相关知识点见《C++ Primer》P293~297.

程序清单:

#include <iostream>
#include <string>

using namespace std;

int main(int argc,char *argv[])
{
    string s("Hello world!");

    string s1 = s.substr();
    cout << s1 << endl;

    string s2 = s.substr(6);
    cout << s2 << endl;

    string s3 = s.substr(6,5);
    cout << s3 << endl;

    string s4("C++ Primer");
    s4.append(" 3rd Ed."); //s4 == "C++ Primer 3rd Ed.";

    /*equivalent to s4.append(" 3rd Ed.")*/
// s4.insert(s4.size()," 3rd Ed.");

    cout << s4 << endl;

    s4.replace(11,3,"4th");
    /*equivalent way to replace "3rd" by "4th"*/
// s4.erase(11,3);

// s4.insert(11,"4th");

    cout << s4 << endl;

    /*不要求删除的文本长度与插入的相同*/
    s4.replace(11,3,"Fourth");
    cout << s4 << endl;

    string name("Yulingui Zhouyujia Gouyongpan");
    string::size_type pos1 = name.find("Zhouyujia");
    cout << pos1 << endl;

    /*find操作区分大小写*/
    string::size_type pos2 = name.find("zhouyujia");
    cout << pos2 << endl;
 
    /*查找任意字符*/
    string::size_type pos3 = name.find_first_of("iuoa");
    cout << "Find character at index: " << pos3
         << " element is "<< name[pos3] << endl;
 
    /*指定查找的起点*/
    string::size_type pos4 = 0;
    while((pos4=name.find_first_of("iuoa",pos4)) != string::npos)
    {
        cout << "Find character at index: " << pos4
             << " element is " << name[pos4] << endl;
        ++pos4;
    }

    /*寻找不匹配点*/
    /*在string对象中寻找第一个非数字字符*/
    string numbers("0123456789");
    string str("1596s8a99");
    string::size_type pos5 = str.find_first_not_of(numbers);
    cout << "The element at index " << pos5
         << " is the first element that is not a number."
         << " The element is " << str[pos5] << endl;
    
    return 0;
}

程序运行结果:
Hello world!
world!
world
C++ Primer 3rd Ed.
C++ Primer 4th Ed.
C++ Primer Fourth Ed.
9
4294967295
Find character at index: 1  element is u
Find character at index: 1  element is u
Find character at index: 3  element is i
Find character at index: 6  element is u
Find character at index: 7  element is i
Find character at index: 11  element is o
Find character at index: 12  element is u
Find character at index: 14  element is u
Find character at index: 16  element is i
Find character at index: 17  element is a
Find character at index: 20  element is o
Find character at index: 21  element is u
Find character at index: 23  element is o
Find character at index: 27  element is a
The element at index 4 is the first element that is not a number. The element is s


阅读(1215) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~