在C ++中找回斜杠(\)

时间:2012-06-08 10:58:44

标签: c++

我在C ++中对反斜杠\的计数有问题,我有这段代码:

string path = "a\b\c";
int level = 0;
int path_length = path.size();
for(int i = 0; i < path_length; i++){
if(path.at(i) == '\\'){
        level++;
    }
}
cout << level << endl;

但是,等级始终为0!你能解释一下原因吗?以及如何计算/的数量?

2 个答案:

答案 0 :(得分:11)

你的字符串无效而不是你期望的那样 - 它应该是string path = "a\\b\\c";

您甚至会收到警告(或至少MSVS提供警告):

  

警告C4129:'c':无法识别的字符转义序列

答案 1 :(得分:9)

变量中的反斜杠应该被转义。

string path = "a\\b\\c";

此外,您可以在算法库中使用count函数,以避免循环字符串中的每个字符并检查它是否为反斜杠。

#include <iostream>
#include <string>
#include <algorithm>   // for count()
using namespace std;

int main()
{
string path = "a\\b\\c";
int no_of_backslash = (int)count(path.begin(), path.end(), '\\');
cout << "no of backslash " << no_of_backslash << endl;
}