计算字符串中尾随空格的数字

Count the number trailing blank space in a string

本文关键字:空格 数字 字符串 计算      更新时间:2023-10-16

谁能帮助我降低下面代码的复杂性,该代码计算字符串中尾随空格的数量。

void main()
{
    string url = "abcd   ";
    int count = 1;
    for (int i = 0; i < url.length(); i++)
    {
        if (url.at(i) == ' ')
        {
            for (int k = i + 1; k < url.length(); k++)
            {
                if (url.at(k) != ' ')
                {
                    count = 1;
                    break;
                }
                else
                {
                    count++;
                    i++;
                }
            }
        }
    }
cout<< count;
}
#include <iostream>
#include <string>
#include <algorithm>
#include <cstring>
using namespace std;
int main()
{
  string url = "abcd    "; // four spaces
  string rev = url;
  reverse(rev.begin(), rev.end());
  cout << "There are " << strspn(rev.c_str(), " ") << " trailing spaces." << endl;
  return 0;
}

我们可以在不反转字符串的情况下做到这一点,也不需要使用 C 函数,如 strspn .例如,查找string::find_last_not_of函数。它将找到字符串中不在指定集合中的最后一个字符,并返回其位置。 如果你的集合是集合" "(空格(,那么它会找到最后一个非空格字符。该位置与字符串长度之间的差异是尾随空格的计数。

#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
  string url = "abcd    "; // four spaces
  size_t last_nonspace = url.find_last_not_of(" ");
  cout << "There are " << url.length() - last_nonspace - 1 << " trailing spaces." << endl;
  return 0;
}

请注意,如果字符串中没有非空格字符(字符串为空或仅包含空格(,则 find_last_not_of 函数返回 string::npos 恰好(size_t) -1,即 size_t 的最大值。当从长度中减去此值,然后减去 1 时,结果值只是长度。算术在所有情况下都有效。

开始向后计算空格

void main() {
    string url = "abcd   ";
    int count = 0;
    for (int i = url.length(); i > 0; i--) {
        if (url.at(i) == ' ') {
            count++;                
        } else {
            break;
        }
    }
cout<< count;
}
您可以使用

find_if(( 算法函数来执行此操作:

#include <algorithm>
#include <string>
#include <cctype>
#include <iostream>
using namespace std;
int main()
{
    string s = "This string has spaces at the end    ";
    string::iterator it = 
         find_if(s.rbegin(), s.rend(), [](char ch) { return !isspace(ch); }).base();
    cout << "The number of trailing spaces is " << std::distance(it, s.end());
}

基本上我们从字符串的末尾开始,让 find_if(( 找到第一个非空格字符(我用 isspace 而不是硬编码的 32(。

之后,返回的迭代器将指向非空格字符,因此只需知道该点和结束之间的"距离"(这就是std::distance将为我们做的事情(。