字符串匹配
我有一个字符串字符串匹配
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
的字符串。
我们该怎么做?
我不知道它会每次或不工作,但我已经尝试过这个,它现在在这个字符串匹配工作。我想知道这是否正确,请给我建议。
str1 = str1.Insert(0, "///");
str1=str1.Insert(str1.Length,"///");
bool Result = mainString.Contains(str1);
与"///RT///"
和"///RATE///"
匹配。
@Marcelo Cantos,我已经更新了这个问题,它是错误的。 – Harikrishna 2010-04-08 10:42:17
酷,我删除了额外的评论。 – 2010-04-08 10:57:15
据我了解您的问题,你想匹配///
作为分隔符之间的字符串。
如果你寻找str
你只需要做Regex.Match(mainString, "(^|///)" + str + "(///|$)");
这可能给你一些线索 - 没有在附近真正的代码质量,并且只有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);
}
}
}
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靠近我所以我不能测试它,但它应该是类似的东西。
*为什么*它应该匹配RT而不是ORDERTIME? *为什么*应该匹配RATE而不是NETRATE? – 2010-04-08 10:35:26
你是什么意思与“匹配”;你只是想检查字符串是否存在? – 2010-04-08 10:35:34
@Jon Skeet先生,因为我想知道在一个字符串中完成匹配的位置? – Harikrishna 2010-04-08 10:41:00