c++ - 计算字符串中尾随空格的数量

标签 c++ string

任何人都可以帮助我降低下面代码的复杂性,该代码计算字符串中尾随空格的数量。

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;
}

我们可以做到这一点,而无需反转字符串,也无需使用像 strspn 这样的 C 函数。例如,查找 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) -1size_t 的最大值。当从长度中减去它,然后减去 1 时,结果值就是长度。该算术在所有情况下都适用。

关于c++ - 计算字符串中尾随空格的数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27597656/

相关文章:

c++ - 在 const 声明的对象上修改可变是未定义的行为吗?

c++ - 如何将选项卡小部件与按钮同步

java - 无法获取此分隔符类

java - 在java中将列表转换为逗号分隔字符串的最佳方法

c# - 有没有一种简单的方法可以用 string.format 只写非空参数

android - android中的随机联系人

c++ - 如何使用在其他文件中定义的 C++ 对象?

c++ - 将 Uint8 转换为 unsigned char RGB 值

c++ - 头文件中的错误 C2719 - 不使用 STL :vector

c# - 在 C# 字符串中丢弃空格后的字符