C ++在比较字符串时忽略前空格,例如:"str1"比较。( " str2" ) = 真
c++ ignore front spaces when comparing strings eg: "str1"compare.(" str2") = TRUE
嗨,我想知道让字符串 str1 看起来等于字符串 str2 的最短方法是什么
str1 = "Front Space";
str2 = " Front Space";
/*Here is where I'm missing some code to make the strings equal*/
if (str1.compare(str2) == 0) { // They match
cout << "success!!!!" << endl; // This is the output I want
}
我只需要它才能让 str1 等于 str2我该怎么做?
我已经进行了多次尝试,但它们似乎都无法正常工作。我认为这是因为字符串中的字符数,即:str1 的字符比 str2 少。
for (int i = 1; i <= str1.length() + 1; i++){
str1[str1.length() - i ] = str1[str1.length() - (i + 1)];
}
任何帮助表示赞赏
如果你可以使用 Boost,可以在 boost/algorithm/string.hpp 中使用修剪函数
str1 = "Front Space";
str2 = " Front Space";
boost::trim_left( str2 ); // removes leading whitespace
if( str1 == str2 ) {
// ...
}
同样,trim
可以删除前导空格和尾随空格。所有这些函数都有*_copy
对应项,它们返回修剪后的字符串而不是修改原始字符串。
如果您不能使用 Boost,创建自己的 trim_left
函数并不难。
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
void trim_left( std::string& s )
{
auto it = s.begin(), ite = s.end();
while( ( it != ite ) && std::isspace( *it ) ) {
++it;
}
s.erase( s.begin(), it );
}
int main()
{
std::string s1( "Hello, World" ), s2( " ntHello, World" );
trim_left( s1 ); trim_left( s2 );
std::cout << s1 << std::endl;
std::cout << s2 << std::endl;
}
输出:
Hello, World
Hello, World
正如其他人所说,您可以使用boost
.如果你不想使用boost
,或者你不能(也许是因为这是家庭作业),很容易制作一个 ltrim 函数。
string ltrim(string str)
{
string new_str;
size_t index = 0;
while (index < str.size())
{
if (isspace(str[index]))
index++;
else
break;
}
if (index < str.size())
new_str = str.substr(index);
return new_str;
}
LLVM也为他们的StringRef类提供了一些修剪成员函数。 这无需修改字符串和复制即可工作,以防这对您很重要。
llvm::StringRef ref1(str1), ref2(str2);
ref1.ltrim();
ref2.ltrim();
if (ref1 == ref2) {
// match
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- 为什么比较运算符如此快速
- 我可以使用 g++ 进行三种比较 (<=>) 吗?
- 比较字符数组
- 将模板化的类型与C++中的某些类/类型进行比较
- C++自定义比较函数
- 如何比较自定义类的std::变体
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- std::设置自定义比较器
- 布尔比较运算符是如何在C++中工作的
- C++将目录中的所有文件与::filesystem进行比较
- shell排序中的交换和比较
- 如何在C++中比较两个char数组
- catch框架有没有办法比较流或文件
- 从文件中读取多个字节,并将它们存储在C++中进行比较
- 智能指针作为无序映射键,并通过引用进行比较
- 比较if语句中的数组值和int值
- 对于循环变体比较
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- C ++在比较字符串时忽略前空格,例如:"str1"比较。( " str2" ) = 真