[C++ API总结]String

目录:

进制转换

字符串转数值

#include<iostream>
#include<string>
#include<sstream>
using namespace std;
int main(){
    string s="20";
    int a,b,c;
    stringstream ss1;
    ss1<<hex<<s;   //以16进制读入流中
    ss1>>a;        //10进制int型输出
    cout<<a<<endl; // 32
    
    stringstream ss2;	
    ss2<<oct<<s;  //以8进制读入流中
	ss2>>b;		  //10进制int型输出
	cout<<b<<endl; // 16
	
	stringstream ss3;
	ss3<<dec<<s;  //以10进制读入流中
	ss3>>c;		  //10进制int型输出
	cout<<c<<endl; // 20
    return 0;
}
————————————————
版权声明:本文为CSDN博主「程序员史迪仔」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/weixin_44668898/article/details/101443574

十进制转16进制

#include <iostream>
#include <sstream>

using namespace std;

int main() {
    int a = 32;
    stringstream stream;
    stream << hex << a; // 使用 std::hex 将整数转换为16进制字符串
    string result( stream.str() ); // 将转换后的字符串保存到result中
    cout << result << endl; // 输出结果,应该输出20

    return 0;
}

创建

使用等号的初始化叫做拷贝初始化,不使用等号的初始化叫直接初始化。

#include<iostream>
#include<string>

using namespace std;

int main(){
    string s;               //  默认初始化,一个空白的字符串
    string s1("ssss");      // s1是字面值"ssss"的副本
    string s2(s1);          // s2是s1的副本
    string s3 = s2;         // s3是s2的副本
    string s4(10, '4');     // s4初始化
    string s5 = "Andre";    // 拷贝初始化
    string s6 = string(10, 'c');    // 可拷贝初始化,生成一个初始化好的对象,拷贝给s6

    char cs[] = "12345";
    string s7(cs, 3);       // 复制字符串cs的前三个字符到s当中

    string s8 = "abcde";
    string s9(s8, 2);

    string s10 = "asdsfasdgf";
    string s11(s10, 3, 4);  // s4是s3从下标s开始4个字符的拷贝,超出s10.size出现未定义
    return 0;
}

追加


string s;
s += 'a';
s.append('a');


// insert原型函数,在index插入count个字符ch。
// insert(size_type index, size_type count, char ch)

string s1 = "abc";
s1.insert(1, 2, 'D')    // "aDDbc"

删除

1、string.erase(pos,n) //删除从pos开始的n个字符 string.erase(0,1); 删除第一个字符

#include <string>
#include <iostream>
 
using namespace std;
 
int main()
{
   string::iterator i;
   string s;
   cin>>s;
   s.erase(1,2);
   cout<<s;
    return 0;
}

2、string.erase(pos) //删除pos处的一个字符(pos是string类型的迭代器)

#include <string>
#include <iostream>
 
using namespace std;
 
int main()
{
   string::iterator i;
   string s;
   cin>>s;
   i = s.begin()+3;
   s.erase(i);
   cout<<s;
    return 0;
}

3、string.erase(first,last) //删除从first到last中间的字符(first和last都是string类型的迭代器)

#include <string>
#include <iostream>
 
using namespace std;
 
int main()
{
   string::iterator i;
   string s;
   cin>>s;
   s.erase(s.begin()+1,s.end()-1);
   cout<<s;
    return 0;
}

查找

1.string中find()返回值是字母在母串中的位置(下标记录),如果没有找到,那么会返回一个特别的标记npos。(返回值可以看成是一个int型的数)

#include<cstring>
#include<cstdio>
#include<iostream>
using namespace std;
int main()
{
    find函数返回类型 size_type
    string s("1a2b3c4d5e6f7jkg8h9i1a2b3c4d5e6f7g8ha9i");
    string flag;
    string::size_type position;
    //find 函数 返回jk 在s 中的下标位置
    position = s.find("jk");
    if (position != s.npos)  //如果没找到,返回一个特别的标志c++中用npos表示,我这里npos取值是4294967295,
    {
        printf("position is : %d\n" ,position);
    }
    else
    {
        printf("Not found the flag\n");
    }
}

2.返回子串出现在母串中的首次出现的位置,和最后一次出现的位置。

  flag = "c";
2      position = s.find_first_of(flag);
3      printf("s.find_first_of(flag) is :%d\n",position); // 5
4      position = s.find_last_of(flag);
5      printf("s.find_last_of(flag) is :%d\n",position); // 25

3.查找某一给定位置后的子串的位置

 //从字符串s 下标5开始,查找字符串b ,返回b 在s 中的下标
2     position=s.find("b",5);
3     cout<<"s.find(b,5) is : "<<position<<endl

4.查找所有子串在母串中出现的位置

//查找s 中flag 出现的所有位置。
    flag="a";
    position=0;
    int i=1;
    while((position=s.find(flag,position))!=string::npos)
    {
        cout<<"position  "<<i<<" : "<<position<<endl;
        position++;
        i++;
    }

循环遍历

string s("abcdefg");
for(string::iterator it = s.begin(); it != s.end(); it++)
{
    cout << *it;
}

//逆向迭代器
for (string::iterator it = s.rbegin(); it != s.rend(); it++)
   { cout << *it;  } 

//采用auto实现迭代器

for(auto itr : s)
{
    cout << itr << endl;
}

拷贝

string s2(s1);          // s2是s1的副本
string s3 = s2;         // s3是s2的副本
    char cs[] = "12345";
string s7(cs, 3);       // 复制字符串cs的前三个字符到s当中

string s8 = "abcde";
string s9(s8, 2);

string s10 = "asdsfasdgf";
string s11(s10, 3, 4);  // s4是s3从下标s开始4个字符的拷贝,超出s10.size

存在/包含

string s = abcdefg, subs = "efg";
int pos = s.find(subs); // 如果找到子字符串则返回首次匹配的位置,否则返回-1
if(pos>0){
    找到
} else {
    没找到
}

判空

string s1 = "012345";
if(!s1.empty()){
    cout << s1.length << endl;
    s1.clear();
}

排序

1. 单个字符串排序
例:string a;  

对 a 进行排序:sort( a.begin(),  a.end() );

2. 字符串数组排序
例:string a[n];

对 a[n] 进行排序: sort(a, a+n) 。

可直接使用 sort,无需重写cmp方法,因为 string 类对 '>' ,'==', '<' 这些比较运算符进行了重载
————————————————
版权声明:本文为CSDN博主「syrdbt」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_38737992/article/details/80209914

数值转字符串

long long m = 1234566700;
string str = to_string(m);   //系统提供数字转字符 

string 和 char* 、char [] 互转

// 直接相等
char str[] = "hello";
string st1 = str;
char* st = "hello";
string st1 = st;


// string 转 char*
char c[20];
string s="1234";
strcpy(c,s.c_str());
 
1、如果要将string转换为char*,可以使用string提供的函数c_str() ,或是函数data(),data除了返回字符串内容外,不附加结束符'\0',而c_str()返回一个以‘\0’结尾的字符数组。

2、const char *c_str();
c_str()函数返回一个指向正规C字符串的指针,内容与本string串相同.
这是为了与c语言兼容,在c语言中没有string类型,故必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式.
注意:一定要使用strcpy()函数 等来操作方法c_str()返回的指针
比如:最好不要这样:
char* c;
string s="1234";
c = s.c_str(); //c最后指向的内容是垃圾,因为s对象被析构,其内容被处理
应该这样用:
char c[20];
string s="1234";
strcpy(c,s.c_str());
这样才不会出错,c_str()返回的是一个临时指针,不能对其进行操作
再举个例子
c_str() 以 char* 形式传回 string 内含字符串
如果一个函数要求char*参数,可以使用c_str()方法:
string s = "Hello World!";
printf("%s",s.c_str()); //输出 "Hello World!"

// string 转 char[]
1     string pp = "dagah";
2     char p[8];
3     int i;
4     for( i=0;i<pp.length();i++)
5         p[i] = pp[i];
6     p[i] = '\0';
7     printf("%s\n",p);
8     cout<<p;
复制代码


子串

string s1 = "Hello World"
string s2 = s1.substr(3, 5);
string s3 = s1.substr(3, str::npos); //截取从下标3到结束的子字符串

split

在C++中,string类本身没有提供拆分字符串的函数。但是可以使用stringstream来拆分字符串。
stringstream和getline配合使用


#include <iostream>
#include <string>
#include <vector>
#include <sstream>

using namespace std;

vector<string> split(string str, char delimiter) {
    vector<string> internal;
    stringstream ss(str); // 将字符串转换为流
    string tok;

    while(getline(ss, tok, delimiter)) { // 使用 getline() 函数从流中获取分隔符前的字符
        internal.push_back(tok);
    }

    return internal;
}

int main() {
    string str = "This is a sample sentence.";
    char delimiter = ' ';

    vector<string> result = split(str, delimiter);

    for(int i=0; i<result.size(); i++) {
        cout << result[i] << endl;
    }
    
    return 0;
}


string 与 数值互转

数值 转 string

法1:
void func3() {
    int i = 123;
    float f = 1.234;
    double d = 2.012;
    cout<<to_string(i)<<endl;
    cout<<to_string(f)<<endl;
    cout<<to_string(d)<<endl;
}
————————————————
123
1.234000
2.012000

法2:
#include <string>
#include <sstream>
#include <iostream>
#include <stdio.h>
using namespace std;
 
int main()
{
    stringstream sstream;
    string strResult;
    int nValue = 1000;
 
    // 将int类型的值放入输入流中
    sstream << nValue;
    // 从sstream中抽取前面插入的int类型的值,赋给string类型
    sstream >> strResult;
 
    cout << "[cout]strResult is: " << strResult << endl;
    printf("[printf]strResult is: %s\n", strResult.c_str());
 
    return 0;
}


string 转 数值

利用 >> 转换为数值
#include <iostream>
#include <sstream>
 
int main(int argc, char *argv[])
{
    for(int i = 0; i < 5; i++)
    {
        std::stringstream ss;
        std::string strNum = std::to_string(i);
        int num;
        ss << strNum;
        ss >> num;
        std::cout << num * num << " ";
    }
    std::cout << std::endl;

————————————————

sprintf用法详解-课外

sprintf 将字串格式化。

  在头文件 #include< stdio.h >中
  语法: int sprintf(string format, mixed [args]...);
  返回值:字符串长度(strlen)
  1. 处理字符方向。-负号时表时从后向前处理。 
  2. 填空字元。 0 的话表示空格填 0;空格是内定值,表示空格就放着。 
  3. 字符总宽度。为最小宽度。 
  4. 精确度。指在小数点后的浮点数位数。 
  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  转换字符
  =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
  % 印出百分比符号,不转换。 
  b 整数转成二进位。 
  c 整数转成对应的 ASCII 字元。 
  d 整数转成十进位。 
  f 倍精确度数字转成浮点数。 
  o 整数转成八进位。 
  s 整数转成字串。 
  x 整数转成小写十六进位。 
  X 整数转成大写十六进位。 
  
  $money = 123.1
  $formatted = sprintf ("%06.2f", $money); // 此时变数 $ formatted 值为 "123.10"
  $formatted = sprintf ("%08.2f", $money); // 此时变数 $ formatted 值为 "00123.10"
  $formatted = sprintf ("%-08.2f", $money); // 此时变数 $ formatted 值为 "123.1000"
  $formatted = sprintf ("%.2f%%", 0.95 * 100); // 格式化为百分比
  
转换为16进制,但是不能使用%b转换为2进制,原因不详
string toBinary64(string retmp) {
    char buff[100];
    int tempp = stoi(retmp, nullptr, 2);
    sprintf(buff, "%x", tempp);
    string xx = buff;
    return xx;
}


转换为2进制
string toBinary(int num) {
    char buff[100];
    itoa(num, buff, 2);
//    sprintf(buff, "%b", num);
    string xx = buff;
    return xx;
}
  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值