【问题标题】:parsing string in c# and putting them into variables在 C# 中解析字符串并将它们放入变量中
【发布时间】:2019-08-31 11:36:28
【问题描述】:

大家好,我是一名学生,还在学习 C#。我需要解析一个具有这种格式的字符串:

< test, 1, 0, 1>

如何提取单词test、数字101,以将它们放入适当数据类型的变量中?

我尝试将其转换为string,然后使用Substring()IndexOf()Split(),但它们都不起作用。

//this is what i did in c but i cant do it in c#
void parseData() {      // split the data into its parts

    char * strtokIndx; // this is used by strtok() as an index

    strtokIndx = strtok(tempChars,",");      // get the first part - the string
    strcpy(messageFromPC, strtokIndx); // copy it to messageFromPC

    strtokIndx = strtok(NULL, ","); // this continues where the previous call left off
    com1 = atoi(strtokIndx);     // convert this part to an integer

    strtokIndx = strtok(NULL, ",");
    com2 = atoi(strtokIndx);     

    strtokIndx = strtok(NULL, ","); 
    com3 = atoi(strtokIndx);     

    //strtokIndx = strtok(NULL, ",");
    //com4 = atof(strtokIndx);     
}

【问题讨论】:

  • 字符串究竟是什么样的? "&lt;test,1,0,1&gt;" 还是 "test,1,0,1"?我的意思是 &lt;&gt; 是字符串的一部分,还是您只是添加它们来标记字符串?
  • @RenéVogt 它旨在成为字符串的一部分,因为它标志着它的开始和结束。
  • 好的,相应地更新了我的答案

标签: c# arrays string parsing char


【解决方案1】:

对于逗号分隔的字符串,您可以使用string.Split():

string input = "<test, 1, 0, 1>";

// first remove the < and >
string inputWithoutBrackets = input.TrimStart('<').TrimEnd('>');

// split the string at the commas
string[] parts = inputWithoutBrackets.Split(',');

string messageFromPC = parts[0].Trim(); // use Trim to get rid of whitespaces
int com1 = int.Parse(parts[1].Trim());
int com2 = int.Parse(parts[2].Trim());
int com3 = int.Parse(parts[3].Trim());

一定要添加错误处理(如果字符串没有足够的,parts 的条目可能少于 4 个。如果没有可解析的数字,int.Parse 可能会抛出异常)。


关于 C# 中字符串的注意事项:它们是 不可变 引用类型。因此,对字符串的每个操作都会返回一个 new 字符串,而不是操作当前实例。例如。 Trim 不会修剪当前实例,而是返回修剪后的字符串。

【讨论】:

    【解决方案2】:

    这听起来像是一项家庭作业/学习任务,我们不为这些任务提供代码。通常,这部分是学习体验不可或缺的一部分。我们能做的就是为您提供总体思路。

    的格式解析一个字符串。如何提取单词“test”和“1”、“0”、“1”

    对于这个特定示例,正确的数据类型是 1 个字符串、3 个整数。关于这一点,您无法一概而论。 .NET 在编译时是强类型的。虽然它对弱类型的事物(例如与 XML WebServices 的交互)具有互操作性,但它们绝对是先进的。

    拆分字符串相对来说是问题的难点。我至少能想到这些解决方案:

    • string.Split(","),在切割任何前导和尾随“”和“”后
    • 对其使用 CSV 解析器(尤其是如果这不是唯一的行)
    • 使用正则表达式 (REGEX)
    • 通过迭代字符的 for 循环手动进行拆分,并将每个字符存储到 string[] 的一个元素中。

    由于 是标记的一部分,CSV 解析器和 REGEX 似乎是最有可能使用的工具。但这真的取决于你以前学到了什么。通常这样的任务是为了强化你之前的教导。

    【讨论】:

    • 它实际上是我的项目论文的一部分,是的,它是最难的部分。我问这个是因为它将是 arduino 和 c# 之间的通信线路。我仍在学习 C#,Regex 似乎是一个不错的选择。谢谢你:)
    猜你喜欢
    • 2020-04-02
    • 1970-01-01
    • 2021-01-10
    • 2016-09-23
    • 2021-04-21
    • 1970-01-01
    • 2018-09-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多