2014-03-13 107 views
-3

我是C#的新手。掃描字符串數組

如何獲取用戶輸入並將每個字母作爲單獨的實體保存在數組中。

我想掃描整個數組,找到一個特定的字符序列作爲起點。

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Console.WriteLine("Please enter Nitrogenous base sequence"); 
      string[] sequence = new string[]{Console.ReadLine()}; 

      foreach(string a in sequence) 
      { 
       if(a=="TATAAT") 
       { 
        Console.WriteLine("YAAY"); 
       } 

       else 
       { 
        Console.WriteLine("NO"); 
+0

我想你可能想改爲使用Console.ReadKey。 – Casey

回答

3

你可以將string想象爲一個榮耀的字符數組。

var pattern = "TATAAT"; 
var input = Console.ReadLine(); 

var patternIndex = input.IndexOf(pattern); 

if(patternIndex >= 0) { 
    var answer = input.Substring(patternIndex + pattern.Length, 4); 
    Console.WriteLine("YAAY: " + answer); 

} else { 
    Console.WriteLine("NO"); 

} 
+0

需要將「TATAAT」後面的下四個字符保存爲單獨的實體。我是否需要將我的原始輸入字符串作爲字符串數組,然後使用索引? – Ashwin

+0

@Ashwin我編輯了我的答案 –

+0

非常感謝,你在哪裏找到所有這些子方法? – Ashwin

0

可以使用LINQ做到這一點,這將讓來自用戶的輸入,然後每個字符保存爲string到一個數組:

string[] sequence = Console.ReadLine().Select(x => x.ToString()).ToArray(); 

如果你不想包含空格:

string[] sequence = Console.ReadLine().Where(x => !char.IsWhiteSpace(x)) 
        .Select(x => x.ToString()) 
        .ToArray(); 
+0

很明顯,op是一個初學者 - 用lambda表達他,並且LINQ需要更多解釋... – joe

+0

仍然覺得很難掃描。需要鍵入隨機組合的字母,然後在找到TATAAT時停止。 – Ashwin