gpt4 book ai didi

c# - 以正确的方式在 C# 中解析字符串

转载 作者:太空宇宙 更新时间:2023-11-03 19:12:43 24 4
gpt4 key购买 nike

如何在 C# 中正确解析字符串?我有下一个模式

"|?\d+(:\d+([lLrR])?)?"

bool bV = 是否有竖线;
然后 int iL = number;
跳过 ':'
然后 int iD = number;
bool bS = 是否有字母。

如果我用C写,我可以自己写成如下:

char* s = str; char* s1 = str1;
if( *s == '|' ) { bV == 1; s++; }
while( isdigit (*s) )
{ *s1 = s++; s1++; } s1 = 0;
iL = itoa (str1);
// and so on..

但在 C# 中它看起来很愚蠢。我阅读了有关 String.SplitRegex.Split 的内容,但在它起作用之后我也需要编写分支。我认为有更好的方法。你知道吗?


我会尽力解释。有专门解析的函数吗?喜欢..

parseString(" {'|' | ''} {0} : {1} {'L'|'R'}", string, int, int, string);

像 ReadConsole 一样,有些地方需要数值。我只是问问。框架有很多有趣的功能。

目前我尝试使用 regexp 并有这样的东西:

 {
string pattern = @"(?<bVect>[|]?)\s*(?<iDest>\d+)(\s*:\s*(?<iLvl>\d+)*\s*(?<bSide>[LRlr]?)?)";
RegexOptions option = RegexOptions.IgnoreCase;
Regex newReg = new Regex(pattern,option);
MatchCollection matches = newReg.Matches(str);

// Here starting 'Branches' = 'if-statements' I mean
if(matches.Count != 1) { /* error */}
bV = (matches[0].Groups["bVect"].Value == "|");
bS = (matches[0].Groups["bSide"].Value != "");
string ss = matches[0].Groups["iDest"].Value;
if (ss != "")
iD = Convert.ToInt32 (ss);
ss = matches[0].Groups["iLvl"].Value;
if( ss != "" )
iL = Convert.ToInt32 (ss);
}

最佳答案

您可以使用[] 运算符直接访问字符串中的字符。从这一点开始,您可以在 C# 中使用您已经工作的 C 算法。

唯一的区别是显然你不能使用指针(除非你想使用不安全的代码,但不推荐)。所以你也必须保留数组的索引而不是使用指针算法。考虑这样的事情:

int index = 0;
if( s[index] == '|' ) { bV == 1; index++ }
/// and so on

关于c# - 以正确的方式在 C# 中解析字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19443795/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com