我正在使用pircbot执行Java IRC API项目,该项目要求我实现天气API。但是,正在测试的某种方式正在处理消息String。我正在尝试这样做-用户输入:
(城市)天气(部分)
例如:Austin天气阵风
这表明用户希望使用天气API来获取Austin中的阵风信息。
为此,我想“拆分”字符串并将(City)和(component)子字符串放入自己的字符串中。我试图这样做:
else if (message.contains("weather")) {
String component;
String city;
int indexA = 0;
int indexB = message.indexOf(" weather");
int indexC = (message.indexOf("weather") + 6);
int indexD = message.length() + 1;
city = message.substring(indexA, indexB);
component = message.substring(indexC, indexD);
startWebRequestName(city, component, sender, channel);
}
似乎没有用,所以我开始在测试课程中进行实验:
public static void main (String args[]) {
String message = "Austin weather gust";
int firstIndex = message.indexOf("weather");
System.out.println(firstIndex);
}
在搞乱之后,indexOf似乎适用于“奥斯丁”中包含的每个字符和子字符串,但此后不再起作用。对于“ Austin”之后的任何内容(例如“ weather”,“ w”或“ gust”),indexOf返回-1,这很奇怪,因为我肯定这些东西在里面哈哈。有任何想法吗?
另外,请让我知道是否需要详细说明。我觉得这解释得很差。
最佳答案
如果可以确保输入字符串始终采用上面给出的格式,并且没有例外,则可以使用以下方法快速获取城市和组件值。
String inputString = "Austin weather gust";
String[] separatedArray = inputString.split(" ");
String city = separatedArray[0];
String component = separatedArray[2];