显然,对于 IRC 机器人,输入是由用户键入单个字符串生成的,通常带有一个命令和一些参数,每个参数之间用空格分隔。我正在使用 Java 编写 IRC 机器人,并希望解析字符长度可能不同的参数,并将它们保存到多个字符串中以供以后使用。我想创建一个如下所示的命令:
bot.command argument1 argument2 argument3
我希望如果消息以 bot.command 开头,那么 user
将存储 argument1
,time
将存储 argument2
,date
将存储 argument3
。但问题是,argument1
、argument2
和 argument3
的字符长度可能有所不同,因此执行诸如 time = message.substring(33, message.length())
之类的操作将在参数末尾停止读取,但它并不总是读取 argument3
文本开始的字符串。我需要检测分隔符空间在哪里,然后开始从一个字符读取 argument3
。我无法使用 If 语句来确定参数可能是什么,因为它们可以是任何东西。如果上面的段落不清楚,这是一个模板:
String message //= the IRC message and bot input
String user;
String time;
String date;
if (message.startsWith("bot.command")) {
user = message.substring(13, detect next space here and stop reading one character before);
time = message.substring(detect where previous space was and start one character after that, end before next space);
date = message.substring(detect where previous space was and start one character after that, message.length());
}
我希望这能说明我正在尝试做的事情。感谢您的帮助!
最佳答案
我建议使用 String.split,它使用分隔符正则表达式将字符串分解为数组。对于您的情况,您可能会这样做:
String[] args = message.split("\\s+");
if (args[0].equals("bot.command"))
{
user = args[1];
...
}
我使用 \s+
模式(匹配一个或多个空白字符)而不只是一个空格进行分割的原因是,这样,如果参数被多个空格或制表符之类的东西分隔开,程序就不会崩溃。
关于Java - 如何检查字符串中下一个即将出现的空格? (对于 IRC 机器人),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23923386/