如何在 C# 中拆分字符串
本文关键字:拆分 字符串 | 更新日期: 2023-09-27 17:55:22
我有一个像这样的字符串
"List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar"
和像这样的List<String>
List<String> l_lstValues = new List<string> { "List_1", "XList_3", "List_2" };
我需要根据l_lstValues
中的值拆分字符串。
所以拆分的子字符串会像
List_1 fooo asdf
List_2 bar fdsa
XList_3 fooo bar
请给我发布一种方法提前致谢
您必须在 msdn 上使用此拆分方法,您必须将 List 传递到一个数组中,然后,您必须作为拆分该数组的参数传递。
我在这里给你留下链接
http://msdn.microsoft.com/en-us/library/tabh47cf(v=VS.90).aspx
如果要维护要拆分的单词,则必须迭代结果数组,然后在列表中添加单词(如果字符串和列表中的顺序相同)。
如果顺序未知,您可以使用 indexOf 在列表中找到单词并手动拆分字符串。
再见
你可以做这样的事情:
string a = "List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar";
List<String> l_lstValues = new List<string> { "List_1",
"XList_3", "List_2" };
var e = l_lstValues.GetEnumerator();
e.MoveNext();
while(e.MoveNext())
{
var p = a.IndexOf(e.Current);
a = a.Insert(p, "~");
}
var splitStrings = a.Split(new string[]{" ~"},StringSplitOptions.None);
所以在这里,每当我遇到列表中的元素时,我都会插入一个~
(第一个除外,因此是外部e.MoveNext()
),然后在~
上拆分(注意前面的空格)最大的假设是字符串中没有~
,但我认为这个解决方案很简单,如果你能找到这样的字符并确保该字符不会出现在原始字符串中。如果字符不适合您,请使用类似 ~~@@
的东西,因为我的解决方案显示字符串拆分string[]
您可以只添加整个字符串进行拆分。
当然,您可以执行以下操作:
foreach (var sep in l_lstValues)
{
var p = a.IndexOf(sep);
a = a.Insert(p, "~");
}
但那会有一个空字符串,我只是喜欢使用 MoveNext()
和 Current
:)
您可以将原始字符串中的每个字符串替换为添加的控制字符,然后在该 caracter 上拆分。例如,您的原始字符串:
List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar
需要成为:
List_1 fooo asdf;List_2 bar fdsa;XList_3 fooo bar
稍后将根据;
进行拆分,产生所需的结果。为此,我使用以下代码:
string ori = "List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar"
foreach (string word in l_lstValues) {
ori = ori.Replace(word, ";" + word);
}
ori = ori.Replace(" ;", ";"); // remove spaces before ;
ori = Regex.Replace(ori, "^;", ""); // remove leading ;
return (ori.split(";"));
您还可以组装以下正则表达式:
('S)('s?(List_1|XList_3|List_2))
第一个令牌('S)
将阻止替换第一个匹配项,第二个令牌's?
将删除空格。现在我们用它来添加;
:
string ori = "List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar"
string regex = "('S)('s?(" + String.Join("|", l_lstValues) + "))";
ori = Regex.Replace(ori, regex, "$1;$3");
return (ori.split(";"));
正则表达式选项有点危险,因为这些单词可以包含替身序列。
你可以做如下的事情:
string sampleStr = "List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar";
string[] splitStr =
sampleStr.Split(l_lstValues.ToArray(), StringSplitOptions.RemoveEmptyEntries);
编辑:修改为打印带有列表词的片段
假设:sampleStr
中没有":
"
foreach(string listWord in l_lstValues)
{
sampleStr = sampleStr.Replace(listWord, ':'+listWord);
}
string[] fragments = sampleStr.Split(':');
这是最简单和直接的解决方案:
public static string[] Split(string val, List<string> l_lstValues) {
var dic = new Dictionary<string, List<string>>();
string curKey = string.Empty;
foreach (string word in val.Split(' ')) {
if (l_lstValues.Contains(word)) {
curKey = word;
}
if (!dic.ContainsKey(curKey))
dic[curKey] = new List<string>();
dic[curKey].Add(word);
}
return dic.Values.ToArray();
}
该算法没有什么特别之处:它迭代所有传入的单词并跟踪用于将相应值排序到字典中的"当前键"。
编辑:我简单地将原始答案与问题更加匹配。它现在返回一个 string[] 数组 - 就像 String.Split() 方法一样。如果传入字符串序列不是以l_lstValues列表中的键开头,则会引发异常。
可以使用 String.IndexOf 方法获取列表中每个短语的起始字符的索引。
然后,您可以使用此索引拆分字符串。
string input = "A foo bar B abc def C opq rst";
List<string> lstValues = new List<string> { "A", "C", "B" };
List<int> indices = new List<int>();
foreach (string s in lstValues)
{
// find the index of each item
int idx = input.IndexOf(s);
// if found, add this index to list
if (idx >= 0)
indices.Add(idx);
}
获得所有索引后,对它们进行排序:
indices.Sort();
然后,使用它们来获取结果字符串:
// obviously, if indices.Length is zero,
// you won't do anything
List<string> results = new List<string>();
if (indices.Count > 0)
{
// add the length of the string to indices
// as the "dummy" split position, because we
// want last split to go till the end
indices.Add(input.Length + 1);
// split string between each pair of indices
for (int i = 0; i < indices.Count-1; i++)
{
// get bounding indices
int idx = indices[i];
int nextIdx = indices[i+1];
// split the string
string partial = input.Substring(idx, nextIdx - idx).Trim();
// add to results
results.Add(partial);
}
}
这是我制作的示例代码。这将获取所需的子字符串,前提是密钥拆分器按顺序从原始字符串的左到右位置。
var oStr ="List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar";
List<String> l_lstValues = new List<string> { "List_1", "List_2", "XList_3" };
List<string> splitted = new List<string>();
for(int i = 0; i < l_lstValues.Count; i++)
{
var nextIndex = i + 1 >= l_lstValues.Count ? l_lstValues.Count - 1 : i + 1;
var length = (nextIndex == i ? oStr.Length : oStr.IndexOf(l_lstValues[nextIndex])) - oStr.IndexOf(l_lstValues[i]);
var sub = oStr.Substring(oStr.IndexOf(l_lstValues[i]), length);
splitted.Add(sub);
}
您可以使用以下代码完成此任务
string str = "List_1 fooo asdf List_2 bar fdsa XList_3 fooo bar";
List<String> l_lstValues = new List<string> { "List_1", "XList_3", "List_2" };
string[] strarr = str.Split(' ');
string sKey, sValue;
bool bFlag = false;
sKey = sValue = string.Empty;
var lstResult = new List<KeyValuePair<string, string>>();
foreach (string strTempKeys in l_lstValues)
{
bFlag = false;
sKey = strTempKeys;
sValue = string.Empty;
foreach (string strTempValue in strarr)
{
if (bFlag)
{
if (strTempValue != sKey && l_lstValues.Contains(strTempValue))
{
bFlag = false;
break;
}
else
sValue += strTempValue;
}
else if (strTempValue == sKey)
bFlag = true;
}
lstResult.Add(new KeyValuePair<string, string>(sKey, sValue));
}