C#等价的C ++ std :: string find

时间:2015-07-28 05:06:39

标签: c# c++ linq

我在c++

中寻找std::string's find c#的等同物

所以在c++你可以拥有:

string s, nucleo = "ATGC";
s = "TCCCTCCATGCAG";
for (int i = 0; i < (int) s.length(); i++) {
      v = append(v, nucleo.find(s[i]));
      ...
}

linq或loop中的nucleo.find会是什么样子?

我目前有

int? found = s.find(nucleo);

public static int? find(this string source, string what)
{
    if (source == null) throw new ArgumentNullException("source");
    if (what == null) throw new ArgumentNullException("what");
    if (source.Length == 0) return null;
    if (what.Length == 0) return 0;
    for (int i = 0; i < source.Length; i++)
    {
        if (source.IndexOf(source[i]) == -1) return i;
    }
    return null;
}

2 个答案:

答案 0 :(得分:2)

using System;

class Program
{
static void Main()
{
// The input string.
const string value = "Your dog is cute.";

// Test with IndexOf method.
if (value.IndexOf("dog") != -1)
{
    Console.WriteLine("string contains dog!");
}
}
} 

或者你可以使用Contains

string s1 = "The quick brown fox jumps over the lazy dog";
string s2 = "fox";
bool b;
b = s1.Contains(s2);
Console.WriteLine("Is the string, s2, in the string, s1?: {0}", b);

答案 1 :(得分:1)

您的C#代码毫无意义 - 当您需要做的就是直接调用它时,看起来您自己重新实现String.IndexOf

C ++&#39; s std::string::find返回第一个匹配的第一个字符(在可选的起始位置参数之后)的位置(即字符索引),这与.NET&#的行为相同39; s String.IndexOf方法。唯一的区别是find在不匹配时返回npos,但IndexOf会返回-1

只需这样做(如果你想使用null作为不匹配的值):

Int32? found = s.IndexOf( nucleo );
if( found == -1 ) found = null;