计算字符串中尾随空格的数字
Count the number trailing blank space in a 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;
}
我们可以在不反转字符串的情况下做到这一点,也不需要使用 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
将为我们做的事情(。
相关文章:
- std::regex:匹配由数字和空格组成的字符串,并提取数字.如何?
- 如何从文件中读取用空格分隔的数字
- 使用正则表达式C++计算数字中的十进制空格
- 有没有办法在带有空格C++源代码中写入大量数字以使其更具可读性?
- 使用 Get 的 C++ 输入被替换为空格、不正确的数字
- 不理解连续数字之间的空格代码
- C++ [std::regex] 尝试仅匹配中间有空格的数字
- 用递增的数字替换字符串中的空格
- 从文件中读取带有空格和数字数据的文本
- 如何从用户那里获得输入字符串而不是示例,然后计算空格、标点符号、数字和字母.C++
- 我有n个空格,在每个空格中,我可以放置一个数字0到m.编写一个程序来输出所有可能的结果.需要帮助:)
- 如果 C++ stdlib 流的解析数字紧跟非空格字符,如何引发错误
- 在 cpp 中使用 getline 输入数组中的空格分隔数字
- 如果字符串中没有空格,如何解析带有数字和字符的字符串并分隔数字和字符
- 从字符串中读取单词C++,同时忽略空格、数字和符号
- 如何将包含空格和数字的句子从大写转换为小写
- 扫描以空格分隔的数字
- C++ - 如何将空格分隔的数字输入数组
- 如何将 std::string 中的所有非字母字符(数字和特殊字符)替换为空格
- 计算字符串中尾随空格的数字