2010-04-08 189 views
0

我有一個字符串字符串匹配

String mainString="///BUY/SELL///ORDERTIME///RT///QTY///BROKERAGE///NETRATE///AMOUNTRS///RATE///SCNM///"; 

現在我有另一個字符串

String str1= "RT"; 

應該只RT要匹配的是字符串mainString的子串,但不與ORDERTIME這也是子串字符串mainString

String str2= "RATE" ; 

而且RATE(STR2)應與RATE要匹配的是字符串mainString的子串,但不與NETRATE這也是串mainString的字符串。

我們該怎麼做?

+0

*爲什麼*它應該匹配RT而不是ORDERTIME? *爲什麼*應該匹配RATE而不是NETRATE? – 2010-04-08 10:35:26

+0

你是什麼意思與「匹配」;你只是想檢查字符串是否存在? – 2010-04-08 10:35:34

+0

@Jon Skeet先生,因爲我想知道在一個字符串中完成匹配的位置? – Harikrishna 2010-04-08 10:41:00

回答

0

我不知道它會每次或不工作,但我已經嘗試過這個,它現在在這個字符串匹配工作。我想知道這是否正確,請給我建議。

str1 = str1.Insert(0, "///"); 
str1=str1.Insert(str1.Length,"///"); 

bool Result = mainString.Contains(str1); 
2

"///RT///""///RATE///"匹配。

+0

@Marcelo Cantos,我已經更新了這個問題,它是錯誤的。 – Harikrishna 2010-04-08 10:42:17

+0

酷,我刪除了額外的評論。 – 2010-04-08 10:57:15

0

據我瞭解您的問題,你想匹配///作爲分隔符之間的字符串。
如果你尋找str你只需要做
Regex.Match(mainString, "(^|///)" + str + "(///|$)");

0

這可能給你一些線索 - 沒有在附近真正的代碼質量,並且只有5分鐘的工作來與這種僞劣解決方案,但沒有做什麼你需要。它聞到很多被警告。

using System; 
using System.Collections.Generic; 
using System.Collections; 
using System.Linq; 
using System.Text; 

namespace test { 
    class Program { 
     static void Main(string[] args) { 
      String mainString="//BUY/SELL//ORDERTIME//RT//QTY//BROKERAGE//NETRATE//AMOUNTRS//RATE//SCNM//"; 


      Hashtable ht = createHashTable(mainString); 



      if (hasValue("RA", ht)) { 
       Console.WriteLine("Matched RA"); 
      } else { 
       Console.WriteLine("Didnt Find RA"); 
      } 


      if (hasValue("RATE", ht)) { 
       Console.WriteLine("Matched RATE"); 
      } 


      Console.Read(); 

     } 


     public static Hashtable createHashTable(string strToSplit) { 
      Hashtable ht = new Hashtable(); 
      int iCount = 0; 

      string[] words = strToSplit.Split(new Char[] { '/', '/', '/' }); 
      foreach (string word in words) { 

       ht.Add(iCount++, word); 
      } 

      return ht; 
     } 
     public static bool hasValue(string strValuetoSearch, Hashtable ht) { 

      return ht.ContainsValue(strValuetoSearch); 

     } 

    } 

} 
+0

String.Split(char [])將分割*這些字符中的任意*字符 - 它不會將其視爲*字符序列*。 – 2010-04-08 11:06:36

+0

它確實得到一個工作散列表,從字符串中的單個項目足以「查找」值 – jpg 2010-04-08 11:10:47

+0

我說的不是很漂亮 – jpg 2010-04-08 11:11:05

0

Linq to Object怎麼樣?

String mainString="///BUY/SELL///ORDERTIME///RT///QTY///BROKERAGE///NETRATE///AMOUNTRS///RATE///SCNM///"; 
String searchTerm = "RT"; 
String[] src = mainString.split('///'); 
var match = from word in src where 
      word.ToLowerInvariant() == searchTerm.ToLowerInvariant() 
      select word; 

我沒有VS靠近我所以我不能測試它,但它應該是類似的東西。