C++string类(3)
7.牛刀小试
7.1 仅仅反转字母
class Solution {
public:bool isLetter(char ch){if (ch >= 'a' && ch <= 'z')return true;if (ch >= 'A' && ch <= 'Z')return true;return false;}string reverseOnlyLetters(string S) {if (S.empty())return S;size_t begin = 0, end = S.size() - 1;while (begin < end){while (begin < end && !isLetter(S[begin]))++begin;while (begin < end && !isLetter(S[end]))--end;swap(S[begin], S[end]);++begin;--end;}return S;}};
7.2找字符串中第一个只出现一次的字符
class Solution {
public:int firstUniqChar(string s) {// 统计每个字符出现的次数int count[256] = { 0 };int size = s.size();for (int i = 0; i < size; ++i)count[s[i]] += 1;// 按照字符次序从前往后找只出现一次的字符for (int i = 0; i < size; ++i)if (1 == count[s[i]])return i;return -1;}};
7.3字符串里面最后一个单词的长度
#include<iostream>
#include<string>
using namespace std;
int main()
{string line;// 不要使用cin>>line,因为会它遇到空格就结束了// while(cin>>line)while (getline(cin, line)){size_t pos = line.rfind(' ');cout << line.size() - pos - 1 << endl;}return 0;
}
7.4验证一个字符串是否是回文
class Solution {
public:bool isLetterOrNumber(char ch){return (ch >= '0' && ch <= '9')|| (ch >= 'a' && ch <= 'z')|| (ch >= 'A' && ch <= 'Z');}bool isPalindrome(string s) {// 先小写字母转换成大写,再进行判断for (auto& ch : s){if (ch >= 'a' && ch <= 'z')ch -= 32;}int begin = 0, end = s.size() - 1;while (begin < end){while (begin < end && !isLetterOrNumber(s[begin]))++begin;while (begin < end && !isLetterOrNumber(s[end]))--end;if (s[begin] != s[end]){return false;}else{++begin;--end;}}return true;}};
7.5字符串相加
class Solution {
public:string addstrings(string num1, string num2){// 从后往前相加,相加的结果到字符串可以使用insert头插// 或者+=尾插以后再reverse过来int end1 = num1.size() - 1;int end2 = num2.size() - 1;int value1 = 0, value2 = 0, next = 0;string addret;while (end1 >= 0 || end2 >= 0){if (end1 >= 0)value1 = num1[end1--] - '0';elsevalue1 = 0;if (end2 >= 0)value2 = num2[end2--] - '0';elsevalue2 = 0;int valueret = value1 + value2 + next;if (valueret > 9){next = 1;valueret -= 10;}else{next = 0;}//addret.insert(addret.begin(), valueret+'0');addret += (valueret + '0');}if (next == 1){//addret.insert(addret.begin(), '1');addret += '1';}reverse(addret.begin(), addret.end());return addret;}};
7.5其它题目
1.翻转字符串Ⅱ:区间翻转
2.翻转字符串Ⅲ:翻转字符串中的单词
3.字符串相乘
4.找出字符串中第一个只出现一次的字符