2016-10-25 123 views
1

我正在使用Cosmos來製作一個簡單的操作系統來理解它。 如果我想創建一個名爲echo的命令行來回應用戶的輸入,首先我需要檢查輸入是否在其前面有「echo」。 例如,如果我輸入「echo hello world」,我希望我的VMware迴應「hello world」,因爲echo是我的新命令行。c#檢查一個字符串是否有某個字

我想什麼是

String input = Console.ReadLine(); 
if (input.Contains("echo")) { 
    Console.WriteLine(input} 
} 

它是沒有效率。首先,VMware表示

IndexOf(..., StringComparison) not fully supported yet! 

而且用戶可以在他的字符串中間型「回聲」,而不是命令。

有沒有任何有效的方法來解決這個問題?

+1

你能使用StartsWith? –

+2

如果你不能使用'IndexOf',我敢肯定你運氣不好,除非你只檢查實際字符if(input [0] =='e'&& input [1] =='c'.. ..)' – juharr

回答

1
if(!string.IsNullOrEmpty(input) && input.StartsWith("echo")) 
     { 
      Console.WriteLine(input); 
     } 

您應該使用StartWith而不是Contains。最好先檢查字符串是否爲空或空。

+0

這個代碼在我的保護覆蓋無效運行(),VMware一旦我輸入任何沒有循環自動退出。你知道爲什麼嗎? –

0

您可以使用空格分隔它,並檢查開關。

String input = Console.ReadLine(); 
String[] input_splited = input.split(' '); 
switch(input_splited[0]){ 
    case 'echo': 
     String value = input_splited[1]; 
     Console.WriteLine(value); 
     break; 
    case 'other_cmd': 
     String other_value = input_splited[1]; 
     break; 
} 

我希望它適用於你。 :)

0

我弄清楚,你需要類似的東西:

 const string command = "echo"; 
     var input = Console.ReadLine(); 

     if (input.IndexOf(command) != -1) 
     {     
      var index = input.IndexOf("echo");    
      var newInputInit = input.Substring(0, index); 
      var newInputEnd = input.Substring(index + command.Length); 
      var newInput = newInputInit + newInputEnd; 
      Console.WriteLine(newInput); 
     } 

     Console.ReadKey(); 
相關問題