【问题标题】:C#: Splitting strings after reading TCP Byte StreamC#:读取 TCP 字节流后拆分字符串
【发布时间】:2016-03-16 09:35:07
【问题描述】:

我正在使用 C# 将 TCP/IP 套接字数据作为字符串读取(例如,在 PLC 编程代码中输入的 LREAL 值,如“2.2214E-18”),然后将其插入 MongoDB。但是,我不想在插入字符串时指定数据库的名称,而是想将它与字符串一起提供。然后,我想拆分字符串并在程序的各个部分中使用这些部分。

有什么办法可以做到吗?

我的目标是在 PLC 端将 '2.2214E-18 database_name collection_name' 作为字符串并在 C# 代码中拆分。

为了读取字节流,使用了这个特定的代码块:

TcpClient client = new TcpClient(hostName, portNum);
StreamReader sr = new StreamReader(client.GetStream());
line = sr.ReadToEnd();

期待您的回复。

【问题讨论】:

    标签: c# tcp


    【解决方案1】:

    这样做:

    string[] plcInfo = line.Split();
    

    string[] plcInfo = line.Split(null);
    

    或:

    string[] plcInfo = line.Split(new char[0]);
    

    您将在一个数组中获得 2 个字符串,第一个元素必须是 2.2214E-18,第二个元素必须是 database_name collection_name

    【讨论】:

    • 第二个字符串是否可以进一步分为两个字符串,比如一个是database_name,另一个是collection_name?
    • 或者只是line.Split();
    • line.Split();...不错的 tnxs
    • 我仍然不知道如何访问这些拆分字符串以便在我的代码中进一步使用。我使用:var mongoDB = server.GetDatabase("test_database"); var collection = mongoDB.GetCollection<MongoDBInfo>("sample.RawData");我如何在上面提到的语句中使用那些拆分字符串?
    • 编辑您的问题并添加此代码,并添加字符串的外观...请
    【解决方案2】:

    您的实际问题似乎是:

    在我控制其格式的字符串中,如何存储多个值以便以后拆分?

    答案很简单:你需要一个分隔符。选择分隔符是困难的部分,它必须是一个永远不会出现在您希望存储的值中的分隔符。

    在这种情况下,管道字符 (|) 似乎是一个安全的选择。所以让你的字符串是这样的:

    string input = "2.2214E-18|database_name|collection_name";
    

    然后您可以拆分该字符并检索您的单独值:

    string[] output = input.Split('|');
    

    然后确保在使用前验证输出:

    if (output.Length != 3)
    {
        throw new ArgumentException("input", "Useful error message here");
    }
    
    string value = output[0];
    string databaseName = output[1];
    string collectionName = ouput[2];
    

    【讨论】:

    • 是的,这正是我要找的。万分感谢。我会检查管道功能。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-16
    • 2011-02-13
    相关资源
    最近更新 更多