如何在字符串中搜索斜杠字符? [英] How can search back slash character in string?
问题描述
你好。我有以下方法。这个方法搜索在字符串实例中获取'\'的计数。但它有错误。
Hi there.I have following method.this method search for getting count of '\' in instance of string. but it has error.
/// <summary>
/// This method returns count of specified character in a string.
/// </summary>
/// <param name="stringForProcessing">Determines instance of string class that contains specifiedCharacter</param>
/// <param name="specifiedCharacter">Determines specified character for searching. </param>
/// <returns></returns>
private int GetCountOfOccurance(string stringForProcessing, char specifiedCharacter)
{
int result = 0;
foreach (char letter in stringForProcessing)
{
if (letter.Equals(specifiedCharacter))
{
result++;
}
}
return result;
}
这里我称之为但不允许编译:
this.GetCountOfOccurance(路径,'\')
请帮帮我。如何搜索'\'
and here i call it but it doesn't allow for compiling:
this.GetCountOfOccurance(path,'\')
Please help me. how can search for '\'
推荐答案
你应该使用转义序列来反斜杠:
http://msdn.microsoft.com/en-us/library/h21280bw.aspx [ ^ ]
You should use the escape sequence for a backslash:
http://msdn.microsoft.com/en-us/library/h21280bw.aspx[^]
this.GetCountOfOccurance(path, '\\');
希望这会有所帮助。
Hope this helps.
两件事:
首先,你需要使用其中两个来逃避反斜杠:
Two things:
First, you need to escape the backslash by using two of them:
this.GetCountOfOccurance(path,'\\');
自反斜杠字符是C#中的特殊字符,它引入了其他字符,如换行符:'\ n' ,引用:'\''和doublequote:'\''。
其次,有很多方法可以做到这一点:在字符串中计算行数 [ ^ ]涵盖了大量的数据!
Since the backslash character is a "special" in C# which introduces other characters such as newline: '\n', quote: '\'' and doublequote: '\"'.
Secondly, there are a huge number of ways to do this: Counting Lines in a String[^] covers a good number of them!
正确转义反斜杠字符,例如
以下行有效
The backslash character smust be properly escaped, e.g.
the following line is valid
char c = '\\'; // compiles fine
而一行以下的行不是
while the line below one is not
char c = '\'; // COMPILATION ERROR
这篇关于如何在字符串中搜索斜杠字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!