[英]Parse a string, create single strings and compare them to a value in an if statement?
我正在尝试做一些看似简单的事情,但我有点受阻,无法将精力全盘绕在上面。
所以基本上我想做的是解析字符串str并创建较小的字符串,并将它们与if语句中的内容进行比较
String str = ("1, 2, 3);
StringTokenizer st = new StringTokenizer(str, ",");
while (st.hasMoreElements()){
//instead of printing the element I want to generate str[i] or something of the sort
System.out.print(st.nextElemenet());
}
//then I want to do this as many times as I have str[i]
if(str1 == 2 || str2 == 3 || str3 == 3){
//do something
}
基本上,我想解析一个字符串,生成一堆较小的字符串,然后在if语句中使用它们。 有任何想法吗? 抱歉,这似乎是一个简单的问题,但我有点卡住了
PS Java 1.4不支持.split,它必须在Java 1.4中。^ _ ^我可以创建一个ArrayList,但是我仍然不确定如何在if中进行迭代,将其所有值与给定值进行比较值。 :/
我认为您需要的是一个String数组。
String[] strArray = new String[st.countTokens()]; // Create an array with no. of tokens as the size
int counter = 0; // Counter variable to be used as the arrays index.
while (st.hasMoreElements()){
//instead of printing the element I want to generate str[i] or something of the sort
strArray[counter++] = st.nextElement(); // add the element to the array
}
这样,您可以将所有标记添加到String数组中,然后可以遍历此数组并比较元素。 现在要对每个元素进行一些if检查 ,您需要循环。 因为您使用的是Java 1.4,所以我使用了标准的for
循环。
for(int i=0; i<strArray.length; i++) {
if(strArray[i].equals("someString")) { // use equals method for string value comparisons.
// do something
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.