字符串

对应练习题:力扣平台

14. 最长公共前缀

cpp 复制代码
class Solution {
public:
    string longestCommonPrefix(vector<string>& strs) {
        string strs1=strs[0];//初始前缀字符串
        for (int i = 1; i < strs.size(); i++) {
            while(strs[i].find(strs1)!=0)//遍历找到共同最长前缀字符串
            {
                strs1=strs1.substr(0,strs1.size()-1);
                if(strs1.empty())//为空返回真
                {
                    return "";
                }
            }
        }
        return strs1;
    }
};

2288.价格减免

cpp 复制代码
class Solution {
public:
    string discountPrices(string sentence, int discount) {
        stringstream sin(sentence),sout;//构造函数
        sout<<fixed<<setprecision(2);//实现两位保存,非四舍五入
        vector<string>words;
        string word;
        while(sin>>word)
        {
            if(word[0]=='$'&&word.size()>1&&all_of(word.begin()+1,word.end(),::isdigit))//判断数字来实现是否到完整单个价格
            {
                double price = stoll(word.substr(1,word.size()-1))*(1.0-discount/100.0);
                sout<<'$'<<price;
            }
            else
            {
                sout<<word;//转变后的
            }
            sout<<" ";
        }
        string ans = sout.str();
        ans.pop_back();
        return ans;
    }
};

1.(解决最长公共前缀问题)find()函数:查找是否存在相同字串 并会返回出现的头位置
2.substr()函数:取子串
// 当某个字符串不以当前前缀开头时,缩短前缀直到找到最长公共前缀
while (strsi.find(prefix) != 0)
{
prefix = prefix.substr(0, prefix.length() - 1);
// 如果前缀为空,表示没有公共前缀,直接返回空字符串
if (prefix.empty())
{
return "";
}
}

3.replace()函数:替换字符
位置得指定,第一个参数是待替换的起始位置,第二个参数是待替换的长度,第三个替换的字符串

4.insert()函数:插入字符 补零情况 str.insert(0, 4, '0');

5.end():最后一个元素的下一个元素,用于检查字符串到末尾

6.字符串流 istringstream ss(字符串)+(ss >> )分割
vector<string> words;
istringstream ss(s); // 使用字符串流来分割字符串
string word;

// 将字符串 s 按照空格分割成单词
while (ss >> word) {
words.push_back(word);
}
7.字符串保留位数,非四舍五入 (sin,sout是构造函数,转换为字符流 类似cin,cout)
getline(cin,s);
stringstream sin(s), sout;
sout << fixed << setprecision(2);
vector<string> words;
string word;
while (sin >> word) {
//all_of()函数会对范围内的每个元素调用谓词函数,如果所有元素都满足谓词函数定义的条件,则返回 true,否则返回 false
if (word0 == '' \&\& word.size() \> 1 \&\& all_of(word.begin() + 1, word.end(), ::isdigit)) { double price = stoll(word.substr(1, word.size() - 1)) \* (1.0 - discount / 100.0); sout \<\< '' << price;
}
else {
sout << word;
}
sout << " ";
}
string ans = sout.str();//获取字符串流方式
ans.pop_back();
return ans;

相关推荐
RS迷途小书童1 小时前
Python 解析大疆无人机 SRT 字幕日志
开发语言·python·无人机
点心的游戏开发世界1 小时前
GDScript 入门笔记(十六):文件读写与数据持久化
开发语言·笔记·游戏引擎·godot
会飞的拖把1 小时前
Python序列详解:列表、元组、字符串的通用操作(超详细版)
开发语言·windows·python
reasonsummer2 小时前
【办公类-115-01】20260906育儿知识(家园小报)批量制作(2026年9月-2027年6月)
开发语言·数据库·c#
君顾12 小时前
智慧场馆解决方案小程序系统实战:从架构设计到上线指南
java·开发语言·智慧场馆
zhougl9962 小时前
Dockerfile实战教程
java·开发语言·spring boot
FfHUCisI2 小时前
Golang 网络轮询器 netpoll:把阻塞 IO 变成事件通知
开发语言·网络·golang
XiaoQiao6669992 小时前
C 语言常用头文件及里面核心函数
c语言·开发语言
statistican_ABin2 小时前
中国宠物经济发展分析报告——基于R语言的2018-2024年宠物市场多维度分析
开发语言·r语言·宠物
matlab代码2 小时前
基于matlab PCA人脸识别系统【源码63期】
开发语言·matlab