字符串

对应练习题:力扣平台

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 (strs[i].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 (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;

相关推荐
眠りたいです19 分钟前
现代C++:C++11并发支持库
开发语言·c++·多线程·c++11·c++并发支持库
小灰灰搞电子25 分钟前
Rust可以取代C++么?
开发语言·c++·rust
cat三三29 分钟前
java之异常
java·开发语言
奇树谦31 分钟前
【Qt实战】实现图片缩放、平移与像素级查看功能
开发语言·qt
Lv117700832 分钟前
Visual Studio中的多态
ide·笔记·c#·visual studio
我命由我1234538 分钟前
Python Flask 开发问题:ImportError: cannot import name ‘Markup‘ from ‘flask‘
开发语言·后端·python·学习·flask·学习方法·python3.11
wjs202441 分钟前
Go 语言指针
开发语言
wuguan_1 小时前
C#:多态函数重载、态符号重载、抽象、虚方法
开发语言·c#
小信啊啊1 小时前
Go语言数组与切片的区别
开发语言·后端·golang