C++string类常见用法(二)

同一部分,完全以代码形式作解

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

int main(){
    string str= "hello ";
    const char *c = "RALPHFJY ";
    str.append(c);
    cout<<str<<endl;

    const char*ch = "and FUNKYA blablabla";
    str.append(ch,10);
    cout<<str<<endl;

    string str1 = " and ";
    string str2 = "forever";
    str.append(str1);
    str+=str2;
    cout<<str<<endl;

    string str3 = "@@@!#";
    str.append(str3.begin()+3,str3.begin()+4);
    cout<<str<<endl;

    str.append(7,'h');
    cout<<str<<endl;

} 
//append的用法 
#include<string>
#include<iostream>
using namespace std;

int main(){
    string str1 ="hello";
    string str2 = "world";

    str1.swap(str2);
    cout<<str1<<endl;
    cout<<str2<<endl; 
} 
#include <iostream>       // std::cout  
#include <string>         // std::string  

int main ()  
{  
  std::string str ("There are two needles in this haystack with needles.");  
  std::string str2 ("needle");  

  // different member versions of find in the same order as above:  
  std::size_t found = str.find(str2);  
  if (found!=std::string::npos)  
    std::cout << "first 'needle' found at: " << found << '\n';  

  found=str.find("needles are small",found+1,6);  
  if (found!=std::string::npos)  
    std::cout << "second 'needle' found at: " << found << '\n';  

  found=str.find("haystack");  
  if (found!=std::string::npos)  
    std::cout << "'haystack' also found at: " << found << '\n';  

  found=str.find('.');  
  if (found!=std::string::npos)  
    std::cout << "Period found at: " << found << '\n';  

  // let's replace the first needle:  
  str.replace(str.find(str2),str2.length(),"preposition");  //replace 用法  
  std::cout << str << '\n';  

  return 0;  
}  

第三处代码来源于网络上的例子

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

int main(){
    string str ="-45";
    int signal = stoi(str);
    cout<<signal<<endl;

    string str2 = "-1.234";
    double signal2 = stof(str2);
    cout<<signal2+3<<endl;

    int num = 123;
    string str3 = to_string(num);
    cout<<str3[1]<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值