2014-10-07 36 views
0

我似乎無法找到一個「好」的方式去執行任務的一個字符串C#字符串操作思路要求

說,如果我有一個字符串,其值是「拿巧克力」 和我使用.Contains方法檢測該字符串是否包含字符串「cola」,並且其中包含「可樂」。我想讓程序獲取「可樂」中的「c」和「a」之後的字符之前的字符,以檢查字符是否都是空格。任何想法如何解決這個問題?任何提示或想法都會很棒!

P.S.我正在製作一個相當廣泛的基於文本的冒險遊戲。

+0

可能[在一個句子找到一個字符串表達式]的重複之後的字符(http://stackoverflow.com/questions/5341407/finding-an-string-expression-in - 句子) – jac 2014-10-07 04:17:40

回答

1
static void Main(string[] args) 
    { 
     string s = "Take Chocolate"; 
     string searchString = "cola"; 

     int beginIndex = 0; 
     int endIndex = 0; 

     if (s.Contains(searchString)) 
     { 
      beginIndex = s.IndexOf(searchString, 0, s.Length); 
      endIndex = beginIndex + searchString.Length; 
     } 

     if(endIndex < s.Length) 
     { 
      Console.WriteLine(s[endIndex + 1]); 

     } 
     else 
     { 
      Console.WriteLine("There is no character after" + searchString); 
     } 

     if(beginIndex > 0) 
      Console.WriteLine(s[beginIndex - 1]); 
     else 
      Console.WriteLine("There is no character before" + searchString); 

    } 

這是一個很小的程序。希望能幫助到你。

+0

我忘記了indexof方法,我絕對可以使用這個 – DurpBurger 2014-10-07 04:29:21

+0

@DurpBurger它可能會產生我寫出來的小錯誤。只需檢查它。 – mybirthname 2014-10-07 04:32:41

+0

#mybirthname我可能會採用使用IndexOf的概念,其餘部分似乎與我的目的不相關,但仍然是很好的代碼。 – DurpBurger 2014-10-07 04:37:38

2

這很簡單。當您檢查.Contains(「可樂」)時,請檢查.Contains(「可樂」)。希望這正是你想要做的。

+2

賠率是OP也願意接受「可樂」在開始或結束時特林,在這種情況下,這是行不通的。 – Gabe 2014-10-07 04:21:24

+0

哇,我可以得到這個工作,我會嘗試和實現這一點。 – DurpBurger 2014-10-07 04:22:24

3

您所描述的內容可以通過regular expressions輕鬆完成。然而,更簡單的方法是將字符串拆分爲空格,然後分析玩家命令的每個部分。

這裏是一個高度簡化的例子,但它得到的想法跨越:

var playerCommand = "Take Chocolate"; 

var parts = playerCommand.Split(); 
// NOTE: use StringComparison.CurrentCultureIgnoreCase for case insensitive comparison 
if (parts[0] == "Take") 
{ 
    if (parts[1] == "Chocolate") 
    { 
     DoTakeChocolate(); 
    } 
    else if (parts[1] == "Cola") 
    { 
     DoTakeCola(); 
    } 
    else 
    { 
     Console.WriteLine("There's no {0} here for you to take", parts[1]); 
    } 
} 

打破文本命令到,因爲它們的初期這樣一個簡單的樹已經在基於文本的冒險遊戲的心臟。

0

如果你的任務是「確定如果短語包含單詞」,你可以短語拆分成單詞,然後檢查他們每個人,

char[] delimiters = [',','.',' ']; // all delimiters that are not letters  
var phrase = "Take Chocolate, and,cola"; 
var containsCola = phrase.split(delimiters).Any(x => x.Equals("cola", StringComparison.OrdinalIgnoreCase); 
0

它在「可樂」中的「C」之前返回字符和的「a」在句子

Class6 c = new Class6(); 
var t = s.ToLower().Replace("cola", "##").Split(new char[] { ',', '.', ' ' }).Where(h => h.Contains("##")).Select(h => c.getFistAndLast(h)); 

    public class class6 { 
    public string getFistAndLast(string word) 
    { 
     string[] words = word.Split(new string[] { "##" }, StringSplitOptions.None); 
     string h = ""; 
     if (words[0].Trim() != "") 
      h = words[0].Remove(0, words[0].Length - 1)+","; 
     if (words[1].Trim() != "") 
      h += words[1][0]; 
     h += " "; 
     return h; 
    } 
    }