字符串

发布于:2024-07-02 ⋅ 阅读:(17) ⋅ 点赞:(0)

对应练习题:力扣平台

14. 最长公共前缀

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.价格减免

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;