zoukankan      html  css  js  c++  java
  • 关于C++String字符串的使用

    要想使用标准C++中string类,必需要包括#include <string>// 注意是<string>。不是<string.h>或cstring,带.h的是C语言中的头文件using std::string;using std::wstring;或using namespace std;
    String类是不可变(final)的,对String类的不论什么改变,都是返回一个新的String类对象.这种话把String类的引用传递给一个方法,该方法对String的不论什么改变,对原引用指向的对象没有不论什么影响,这一点和基本数据类型相似.

    1
    2
    3
    4
    Strings1,s2;
    s1="abc";
    s2=s1;
    s2="def";
    //这样操作之后s1是"abc",s2是"def".
    1
    2
    3
    4
    5
    6
    stringa="hello,world!";
    stringb="hello,world!";
    stringc="hello!";
    stringa="hello,world!";
    stringb="hello,world!";
    stringc="hello!";
    a 和 b 是不是指向同一个地址呢,这个问题在各论坛都是谈论非常激烈。事实上非常easy,跟下这些字符串的内存地址就好了
    1
    stringa="hello,world!";
    1
    2
    00000042moveax,dwordptrds:[02A62208h]
    00000048movdwordptr[ebp-44h],eax
    1
    stringb="hello,world!";
    1
    2
    0000004bmoveax,dwordptrds:[02A62208h]
    00000051movdwordptr[ebp-48h],eax
    1
    stringc="hello!";
    1
    2
    00000054moveax,dwordptrds:[02A756F8h]
    0000005amovdwordptr[ebp-4Ch],eax
    a的地址指向02A62208h,b的地址也是02A62208h,这说明了什么,创建b的时候.net机制肯定是先去查找内存中是否有这个字符串的内存地址,假设有则指向,没有才创建

    #include <iostream>
    #include <algorithm>
    #include <string>
    using namespace std;
    int main()
    {
        string str;
        cin >> str;
    //	int t=strlen(str);
    	cout<<str.length()<<endl;
    	cout<<str.begin()<<"    "<<str[0]<<str[1]<<str[2]<<"   "<<str.end()<<endl;
        sort(str.begin(), str.end());
        cout << str << endl;
        return 0;
    }

    注意这个样例,说明string字符串无法再使用C字符串函数了。

    相关函数:

    Constructors 构造函数。用于字符串初始化
    Operators 操作符。用于字符串比較和赋值
    append() 在字符串的末尾加入文本
    assign() 为字符串赋新值
    at() 按给定索引值返回字符
    begin() 返回一个迭代器,指向第一个字符
    c_str() 将字符串以C字符数组的形式返回
    capacity() 返回又一次分配空间前的字符容量
    compare() 比較两个字符串
    copy() 将内容复制为一个字符数组
    data() 返回内容的字符数组形式
    empty() 假设字符串为空,返回真
    end() 返回一个迭代器,指向字符串的末尾。(最后一个字符的下一个位置)
    erase() 删除字符
    find() 在字符串中查找字符
    find_first_of() 查找第一个与value中的某值相等的字符
    find_first_not_of() 查找第一个与value中的全部值都不相等的字符
    find_last_of() 查找最后一个与value中的某值相等的字符
    find_last_not_of() 查找最后一个与value中的全部值都不相等的字符
    get_allocator() 返回配置器
    insert() 插入字符
    length() 返回字符串的长度
    max_size() 返回字符的最大可能个数
    rbegin() 返回一个逆向迭代器,指向最后一个字符
    rend() 返回一个逆向迭代器,指向第一个元素的前一个位置
    replace() 替换字符
    reserve() 保留一定容量以容纳字符串(设置capacity值)
    resize() 又一次设置字符串的大小
    rfind() 查找最后一个与value相等的字符(逆向查找)
    size() 返回字符串中字符的数量
    substr() 返回某个子字符串
    swap() 交换两个字符串的内容

  • 相关阅读:
    C#运行Javascript脚本Utility
    SQL Mail XPs Options
    TSQL AVG Functions
    eclipse编译时过滤SVN版本控制信息方法(转)
    追MM与设计模式
    android的性能调优
    对象的赋值和复制(转)
    SVN Working Copy xxx locked and cleanup failed
    HTTP协议详解(转)
    atoi和itoa函数的实现
  • 原文地址:https://www.cnblogs.com/wgwyanfs/p/7101890.html
Copyright © 2011-2022 走看看