C#-问题与字符串拆分
C#-问题与字符串拆分
我有一组基于它的值,我已经根据它们来拆分字符串。
例如:输入字符串为
*A/AB(M!@12:6?SIMPLE!+5+2
输出:
[0]: ""
[1]: "A"
[2]: "AB"
[3]: "M"
[4]: "12"
[5]: "6"
[6]: "SIMPLE"
[7]: "5"
[8]: "2"
例如:输入字符串为
*A(M!@12?SIMPLE!+5+2/AB:6
输出:
[0]: ""
[1]: "A"
[2]: "M"
[3]: "12"
[4]: "SIMPLE"
[5]: "5"
[6]: "2"
[7]: "AB"
[8]: "6"
我面临的问题是:如何将A与客户、AB与公司等相关联,因为用户输入这些信息的顺序是随机的。
如果用户没有输入其中任何一个值,它将改变结果的长度。
在C#中拆分字符串时遇到的问题可能是由于没有使用正确的方法来拆分字符串。解决这个问题的方法是使用正则表达式的命名捕获组,并用名称索引匹配项。
可以参考MSDN页面或Stack Overflow上的帖子来获取更多关于使用正则表达式和命名捕获组的信息。
以下是一个示例来帮助你开始使用命名捕获组:
using System; using System.Text.RegularExpressions; class Program { static void Main(string[] args) { Regex regex = new Regex(@"(?:\*(?\w+))|(?:/(? \w+))",RegexOptions.Compiled); string input = "*A/AB(M!:6?SIMPLE!+5+2"; foreach (Match match in regex.Matches (input)) { if (match.Groups["client"].Success) { Console.WriteLine("Client = {0}", match.Groups["client"].Value); } else if (match.Groups["company"].Success) { Console.WriteLine("Company = {0}", match.Groups["company"].Value); } } } }
我知道正则表达式的语法一开始可能很难理解,但它们是一种非常强大的工具,特别适用于这种文本操作。
此外,还有一些工具可以帮助你试验和编写正则表达式,例如Expresso和The Regulator。
使用上述代码可以得到用户输入的任意顺序的分隔符的起始位置列表,然后可以使用substring方法检索值。
然而,存在一个问题,即将字符串分割成子字符串时出现错误。
这个问题的出现原因是在代码的最后一行,即使用substring方法时没有正确使用分隔符的起始位置。
为了解决这个问题,我们需要根据分隔符的起始位置来正确地使用substring方法。以下是解决方法的代码示例:
SortedListlist = new SortedList (); string[] seperator = new string[9]; seperator[0] = "*"; //is the client seperator[1] = "/"; //is the name of company seperator[2] = "("; //name of the market seperator[5] = ":"; //ID seperator[6] = "?"; //orderType seperator[3] = "!@"; //realtive Time seperator[4] = "!+"; // seperator[7] = "+"; //quantity seperator[8] = "@";//price string val = "*A/AB(M!:6?SIMPLE!+5+2"; // Add the positions of separators to the list for (int iSep = 0; iSep < seperator.Length; iSep++) list.Add(val.IndexOf(seperator[iSep]), val); // Retrieve the values using substring foreach (var position in list.Keys) { int length = 0; if (list.IndexOfKey(position + 1) != -1) length = list.Keys[list.IndexOfKey(position + 1)] - position; else length = val.Length - position; string value = val.Substring(position, length); Console.WriteLine(value); }
通过上述代码,我们可以正确地将字符串分割成子字符串,并获取到正确的值。
C#-问题出现的原因是字符串分割时遇到了困难。解决方法是通过对输入字符串进行一系列的替换操作,使其变得更易处理。例如,可以使用Replace()
方法将特殊字符替换为逗号和等号,然后再进行字符串分割操作。
首先,我们可以使用Replace()
方法将"*"替换为",Client=",将"/"替换为",Company=",将输入字符串转换为更易处理的格式。代码如下:
inputString = inputString.Replace("*", ",Client=").Replace("/", ",Company=");
然后,我们可以使用逗号进行字符串分割,将字符串分割成带有标题的列表。代码如下:
string[] stringList = inputString.Split(",");
最后,我们可以使用等号进行字符串分割,将每个字符串进一步分割为标题和值。代码如下:
foreach (string s in stringList) { string[] keyValue = s.Split("="); string heading = keyValue[0]; string value = keyValue[1]; // 进一步处理标题和值 }
通过这种方式,我们可以将输入的字符串成功地分割成包含标题和值的列表,并能够进一步处理每个字符串的标题和值部分。这样,我们就解决了C#中字符串分割的问题。