Reputation: 25058
I'm looking for the equialent of c++
std::string's find
in c#
So in c++
you can have:
string s, nucleo = "ATGC";
s = "TCCCTCCATGCAG";
for (int i = 0; i < (int) s.length(); i++) {
v = append(v, nucleo.find(s[i]));
...
}
How would nucleo.find in linq or loop would look like?
I currently have
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;
}
Upvotes: 0
Views: 2760
Reputation: 155543
Your C# code makes no sense - it looks like you're re-implenting String.IndexOf
yourself when all you need to do is call it directly.
C++'s std::string::find
returns the position (i.e. character-index) of the first character of the first match (after the optional start position parameter), this is identical behaviour to .NET's String.IndexOf
method. The only difference being that find
returns npos
on no-match but IndexOf
returns -1
.
Simply do this (if you want to use null
as a value for no-match):
Int32? found = s.IndexOf( nucleo );
if( found == -1 ) found = null;
Upvotes: 1
Reputation: 2123
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!");
}
}
}
Or may be you can use 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);
Upvotes: 2