如何在c#中使用C语言的strchr函数。请给我一些指导......
答案 0 :(得分:4)
string.IndexOf
答案 1 :(得分:0)
string.IndexOf
就是答案。
但是,如果您正在寻找
strchr功能 returns to the first occurrence of Character to be located in string, or NULL if c is not found
你可以做如下的事情:
创建一个函数
/// <summary>
/// Function: Strchr
/// Returns the first occurrence of Character to be located
/// in string or null otherwise
/// </summary>
/// <param name="originalString"></param>
/// <param name="charToSearch"></param>
/// <returns></returns>
private int? Strchr(string originalString,char charToSearch)
{
int? found = originalString.IndexOf(charToSearch);
return found > -1 ? found : null;
}
并将其称为:
string test = "hello";
int? res = Strchr(test, '3'); //Returns null
int? res = Strchr(test, 'h'); //Returns 0
希望这能回答你的问题。
答案 2 :(得分:0)
上面的答案似乎并没有100%理解strchr()的契约,也没有提供真正的直接替换......它通常会返回一个指向从该字符开始的字符串的指针(不是索引)。
A&#34;更纯粹&#34;实现:
警告:不确定这是否尽可能纯,因为它可能会提供一个 new 字符串而不是指向原始字符串,就像在C ++中一样。可能无法获得真正的substr指针。但我自己并不是C#专家。
/// <summary>
/// C++ strchr Equivalent
/// </summary>
/// Let you fill out the stupid <param ...> tags.
private string strchr(string originalString, char charToSearch)
{
int found = originalString.IndexOf(charToSearch);
return found > -1 ? originalString.Substring(found) : null;
}
但是我也发现这个实现更好b / c你可以简单地对字符串进行+ 1 +的C ++ ptr数学运算来获得终结符...
/// <summary>
/// C++ strchr Equivalent (with jump past character option)
/// </summary>
/// <param name="originalString"></param>
/// <param name="charToSearch"></param>
/// <param name="pastIt"></param>
/// <returns>String starting at the search char</returns>
private string strchr(string originalString, char charToSearch, bool pastIt)
{
int found = originalString.IndexOf(charToSearch);
return found > -1 ? originalString.Substring(found + (pastIt ? 1 : 0)) : null;
}
/// <summary>
/// C++ strchr Equivalent (Pure)
/// </summary>
private string strchr(string originalString, char charToSearch)
{
return strchr(originalString, charToSearch, false);
}