首页 > 解决方案 > 如何高效解析?

问题描述

假设我要解析以下字符串:“01:12 Joseph We will have a meeting at 6 PM.”。在 CI 中可以做(伪代码):

struct data {
    char *time;
    char *name;
    char *message;
};

char *string = "01:12 Joseph We will have a meeting at 6 PM."
struct data notification;
notification.time = strtok(string, " ");
notification.name = strtok(NULL, " ");
notification.message = strtok(NULL, " ");
puts(notification.time); // prints the time it was sent
puts(notification.name); // prints the name of the sender
puts(notification.message); // prints the message content

请注意,我仍在使用相同的缓冲区,我认为这是使用 kotlin 的最佳方式。现在的问题是,将所有数据留在同一个缓冲区中更好还是创建一个新对象用于时间,另一个用于名称,另一个用于消息?

您应该将此视为不断出现的新通知流,您必须解析每个通知以便将其定位在窗口内的任何位置,这对于聊天应用程序等很有用。因此,对于这种用例来说,这是最好的。

标签: kotlin

解决方案


最简单的方法可能是:

val (time, name, message) = s.split(" ", limit=3)

https://pl.kotl.in/s7jznsszJ


推荐阅读