0

There is a perl function that finds and prints all the overlapping k-mers of the input string.

#!/pkg/bin/perl -w

print "Input the string\n";
$dna = <>;
chomp $dna;
print "Input the length of the window\n"; 
$k = <>;
chomp $k;

while (length($dna) >= $k) {
$dna =~ m/(.{$k})/; 
print "$1 \n";
$dna = substr($dna, 1, length($dna) -1);;
}

I would like to make it a function so instead of a string it receives a list of strings and get all k-mers, so I am trying something like:

//first try with defined string and k to see if it works
string dna="ATTTGGC\nTGCCTTA\nCGGTATC\nGAAAATT";
dna.Replace("\n", "");  //instead of chomp
int k=3;
while(dna.Length  >= k){
  //here I do not know how to traslate $dna =~ m/(.{$k})/; 
  //print "$1 \n";
  //$dna = substr($dna, 1, length($dna) -1);;
}

what would be the best way to translate that function from perl to c#?

1 Answer 1

1

You should use Regex's Match method.

string dna = "ATTTGGC\nTGCCTTA\nCGGTATC\nGAAAATT";
dna = dna.Replace("\n", "");
int k = 3;
var r = new Regex(@"(.{" + k + @"})");
while (dna.Length >= k)
{
    Match m = r.Match(dna);
    Console.WriteLine(m.ToString());
    dna = dna.Substring(1);
}

Note that since strings in C# are immutable, you have to do dna = dna.Replace... for it to have an effect.

This prints ATT, TTT, TTG, etc. just like your Perl method. This could be rewritten as a simpler loop and Substring, and avoid regex entirely.

Sign up to request clarification or add additional context in comments.

2 Comments

So it would be fast to do it without regex? That is true for every string length right?. What would be the best way to do it int k=3; for(int i=0; i< dna.Length+1; i+=k){ ... } ?
i would only increment by 1, since that's how far you want to move the starting place by, so use i++ (k comes into play in knowing how long each substring should be and in knowing the max i to go to); and you're going too far, it should be some amount less than dna.Length. You're on the right track to write and debug it yourself, though.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.