【C++】string (含字符串数组)相关用法

34 篇文章 53 订阅
21 篇文章 1 订阅

前言

1、在 Leetcode 做题时,便想顺道总结下 string 的一些用法,免得忘了。

2、博主用的是线上网页来运行 C++ 代码,感兴趣的朋友可以用,挺简洁的。

https://ideone.com/

3、遇到感兴趣的 string 用法,本文相应增加修改。

 

一、截取字符串中的字符 substr

1、常用格式:

// 默认截取从 0 到 npos.
// 重载原型为string substr(_off = 0,_count = npos);
// npos 一般表示为 string 类中不存在的位置, _off表示字符串的开始位置,_count截取的字符的数目
substr()

// 设字符串长度为 n,从字符串下标为 3 开始,向后截取到下标 n - 1 为止
substr(3)

// 从字符串下标为 0 开始,向后截取 x 位
substr(0, x)

2、演示代码

#include<string>
#include<iostream>
using namespace std;
int main()
{
    string str="Welcome to my blog";

    cout<<str.substr()<<endl;

    cout<<str.substr(3)<<endl;//截取 str[5] 到结尾

    cout<<str.substr(0,3)<<endl;//以 str[0]为始,向后截取3位(包含x[0])

    cout<<str.size()<<endl;  // 获取 str 长度
}

 

二、获取 string 字符串长度

1、常用方式:

// 用于获取字符串的长度,可用 str.size();
string str = "welcome";
cout<< str.size() <<endl;  // 7,第一种方法
cout<< str.length() <<endl;  // 7,第二种方法
cout<< strlen(str.c_str()) <<endl;  // 7,第三种方法,常用于 C 语言

/*
c_str()函数返回一个指向C字符串的指针常量,
指向的内容是字符串对象的当前内容加上一个额外的终止字符(‘\ 0’)。
因为在c语言中没有string类型,
所以必须通过string类对象的成员函数c_str()把string 对象转换成c中的字符串样式。
*/

// 用于获取字符串数组的长度,可用 sizeof(strs)/sizeof(string)
string strs[] = {"Welcome", "to", "my", "blog"};
cout<< strs->size() <<endl;  // 等价于strs[0].size(),答案为 7
cout << strs[0].size() << endl;	// 7
cout << strs[1].size() << endl;	// 2

cout<< sizeof(strs) <<endl;  // 128
cout<< sizeof(strs)/sizeof(string) <<endl;  // 4,求字符串数组 strs 的长度,第一种方法
cout<< sizeof(strs)/sizeof(strs[0]) <<endl;   // 4,第二种方法
	
// cout << strs[1][0] <<endl;  // 输出 t

2、演示

 

三、排序

1、用 sort 、reverse 排序

sort(first_pointer, first_pointer + n, cmp)

// 该函数可以给数组,或者链表list、向量排序。
// 参数1:数组的首地址,一般写上数组名就可以,因为数组名是一个指针常量。
// 参数2:首地址加上数组的长度 n(代表尾地址的下一地址)。
// 参数3:默认不填按数组升序排序。

2、上代码

#include <iostream>
#include <algorithm>
#include<cstring>

using namespace std;
int main()
{
	string str = "welcome";
	sort(str.begin(), str.end());  // 头文件记得加上 #include <algorithm>
	cout<< str.c_str() <<endl; 
	
	reverse(str.begin(),str.end());  // 反向排序
	cout<< str.c_str() <<endl; 
	
	// 字符串数组
	string strs[] = {"Welcome", "to", "my", "blog"};
	int n = sizeof(strs)/sizeof(strs[0]);
	sort(strs, strs+n);   // 正序
	for(int i = 0; i < n; i++){
		cout<< strs[i] <<' ';
	}
	cout<<endl;
	reverse(strs, strs+n);  // 反序
	for(int i = 0; i < n; i++){
		cout<< strs[i] <<' ';
	}


}

/* 输出:
ceelmow
womleec
Welcome blog my to 
to my blog Welcome 
*/

3、演示

 

4、还有一种方法,参考了 C++ string数组字符串排序 sort

#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;
 
void sort_string(string *in_array, int n, string *out_array)
{
	vector<string> strArray;
	int i, j = 0;
	for (int i = 0; i < n; i++)
	{ 
		strArray.push_back(in_array[i]);  
        // push_back 函数将一个新的元素加到vector的最后面,位置为当前最后一个元素的下一个元素
	}

	sort(strArray.begin(), strArray.end()); // 正序
	vector<string>::iterator st;
    // string字符串对象的迭代器iterator实现其中之一的格式(正向迭代器):
    // 容器类名::iterator  迭代器名; 

	for (st = strArray.begin(); st != strArray.end(); st++)
	{
		//cout << *st << endl;   //打印结果
		out_array[j++] = *st;
	}
}
 
int main()
{
	//string str[4] = {"Welcome", "to", "my", "blog"};
	string str[5];
    int i = 0;
    while(cin >> str[i++]){
        if(i == 4) break;
    }
	string str_out[4];
	sort_string(str, 4, str_out);
	for (int j = 0; j < 4; j++)
	cout << str_out[j] << ' ';
}

// 输出:
// Success #stdin #stdout 0s 5696KB
// blog my to welcome 

 

5、Leetcode,翻转字符串里的单词,下面是一位大佬写的解法,感兴趣的朋友可以点下面链接去了解

https://leetcode-cn.com/problems/reverse-words-in-a-string/solution/fan-zhuan-zi-fu-chuan-li-de-dan-ci-by-leetcode-sol/

#include <string>  
#include<algorithm>
#include<iostream>
using namespace std;  
int main ()  
{  
	string s("Welcome to my blog");  
    reverse(s.begin(), s.end());
    int n = s.size();
    int idx = 0;
    for (int start = 0; start < n; ++start) {
	    if (s[start] != ' ') {
	        if (idx != 0) s[idx++] = ' ';   // 填一个空白字符然后将idx移动到下一个单词的开头位置
	        
	        int end = start;
	        while (end < n && s[end] != ' ') s[idx++] = s[end++];    // 循环遍历至单词的末尾
	
	        reverse(s.begin() + idx - (end - start), s.begin() + idx);   // 反转整个单词
	
	        start = end;    // 更新start,去找下一个单词
	    	
	    }
    }
    
    s.erase(s.begin() + idx, s.end());
    for(int i = 0 ; i < s.size(); i++){
        if(s[i] == ' '){ cout<<' '; }
        else{  cout<< s[i];  }
    }
}  

 

四、删除字符串中的字符 erase

1、上代码

#include <string>  
#include<iostream>
using namespace std;  
int main ()  
{  
  string str ("Welcome to my blog");  
  string str1 ("Welcome to my blog my friends."); 
  string str2 ("I'm reading an book."); 
  cout<<"size: "<< str2.size() <<endl;   //size: 18
  
  str.erase (7, 4);         // 删除从下标为 7 开始的 4 个字符,即删除下标为 7,8,9,10 的字符
  cout<< str <<endl;        // Welcomemy blog
  str.erase (0, 1);         // 删除从下标为 0 开始的 1 个字符,即删除下标为 0 的字符
  cout<< str <<endl;        // elcomemy blog
  
  cout<< str1[9] <<endl;    // 下标为 9 的字符,即 o
  str1.erase (str1.begin()+9);  // 删除下标为 9 的字符
  cout<< str1 <<endl;        // Welcome t my blog my friends.
  cout<< str1.erase(6) <<endl;    // Welcom,删除从下标为 6 开始之后的字符
  
  str2.erase (str2.begin()+3, str2.end()-4);    //删除从下标为 3 到下标为 size-1-4 之间字符
  cout<< str2 <<endl;        // Welblog
  
}  

2、演示

 

五、以空格分割字符串

1、上代码

#include <iostream>
#include <algorithm>
#include<cstring>
#include <sstream>
#include<vector>

using namespace std;
int main()
{
	string str = "welcome to my blog";
	
	//第一种方法:利用 stringstream 流来处理
    string temp;
	stringstream output;
    output << str;  // 以空格为分隔符,读取 str 字符串到 output 中

    string res[4];
    int i = 0;
    while (output >> temp){
    	res[i++] = temp;
    }
    for (int i = 0; i < 4; i++) {
        cout << res[i] << "***";
    }

/* 还可以用向量来存储,力扣上总是喜欢用vector:
    vector<string> result;
    output << str;
    while (output >> temp)
        result.push_back(temp);
    for (int i = 0; i < result.size(); i++) {
        cout << result[i] << ",";
    }
*/

    //第二种方法:利用 strtok 函数,但分割的数组类型是 char
    char ch[] = "welcome to my blog";
    const char *temp = " ";
    char *res1;
    res1 = strtok(ch, temp);  //原型: char *strtok(char *str, const char *delim); 
    while(res){
    	cout<< res1 <<endl;
    	res1 = strtok(NULL, temp);   // 终止程序无休止地运行
    }

    return 0;
}

 

2、演示

 

 

3、力扣 (LeetCode) 题:https://leetcode-cn.com/leetbook/read/array-and-string/c8su7/

反转字符串中的单词 III
给定一个字符串,你需要反转字符串中每个单词的字符顺序,同时仍保留空格和单词的初始顺序。

示例:

输入:"Let's take LeetCode contest"
输出:"s'teL ekat edoCteeL tsetnoc"

提示:在字符串中,每个单词由单个空格分隔,并且字符串中不会有任何额外的空格。

根据这题,再利用#include <sstream>,写了个小代码:

#include <iostream>
#include <algorithm>
#include<cstring>
#include <sstream>
#include<vector>
 
using namespace std;
int main()
{
	string str = "Let's take LeetCode contest";

    string temp;
	stringstream output;
 
    vector<string> result;
    output << str;
    while (output >> temp)
        result.push_back(temp);
        
    for (int i = 0; i < result.size(); i++) {
        reverse(result[i].begin(), result[i].end());
    }
    for (int i = 0; i < result.size(); i++) {
        cout << result[i] << " ";
    }
 
    return 0;
}

 

附上这题大神的解法:

class Solution {
public:
    string reverseWords(string s) {
        int l = 0,r;
        char temp;
        for(int i=0; i < s.size(); i++){
            if(s[i+1] == ' '|| i + 1 == s.size()){
                r = i;
                while(r > l){
                    temp = s[r];
                    s[r] = s[l];
                    s[l] = temp;
                    r--;
                    l++;
                }
                l = i + 2;
            }
        }
        return s;
    }
};

 

题外话

string 的用法永不止上述,大家可学习参考下面的网址,博主在这里就不一一列举了。

cplusplus: string

C++中的String的常用函数用法总结

C++ 中string数组怎么求长度(元素个数)

C++迭代器一:string字符串对象的迭代器iterator实现、实现vector容器的迭代器

 

  • 23
    点赞
  • 182
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

住在阳光的心里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值