[英]Trouble splitting up a String using indexOf in java
我正在使用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];
请找到以下评论。
private static void cityFetcher(String message) {
if (message.contains("weather")) {
String component;
String city;
int indexA = 0;
int indexB = message.indexOf(" weather");
int indexC = (message.indexOf("weather") + 6);
System.out.println(indexC); //13
int indexD = message.length() + 1;
System.out.println(indexD);//20
city = message.substring(indexA, indexB);
System.out.println(city);//Austin
component = message.substring(indexC, indexD);//if no -1 then ooi bound exception as your trying to access until 20th element. When your input size is only 19.
System.out.println(component);// r gust
}
解。 如果您输入的格式与您声称的相同,则可以使用这两种格式中的任何一种。
private static void cityFetcher(String input){
//Solution 1
String[] params=input.split("\\s");
for(String s:params){
System.out.println(s);
}
//Solution 2
String city=input.substring(0,input.indexOf(" "));
System.out.println(city);
String component=input.substring(input.lastIndexOf(" ")+1,input.length());
System.out.println(component);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.