Java字符串包含两种类型的单词。第一类词语是:
Wx1,Wx2,Wx3,Wx4,Wx5,Wx6, Wx7 etc.第二类词语如下:
Wy1,Wy2 etc. 给定的
String str= "Wx1 Wx2 Wy1 Wx3 Wx4 Wy2 Wx5 Wx7 Wx8"第一类由function1()处理,第二类由function2()处理,function3()进一步处理function1()的级联输出。
function1(Wx1) gives String S1
function1(Wx2) gives String S2
String S12= S1 + S2;
function3(S12) returns String str1
function2(Wy1) gives String Y1
function1(Wx3) gives String S3
function1(Wx4) gives String S4
String S34= S3 + S4;
function3(S34) returns String str2
function2(Wy2) gives String Y2
function1(Wx5) gives String S5
function1(Wx6) gives String S6
function1(Wx7) gives String S7
function1(Wx8) gives String S8
String S5678 = S5 + S6 + S7 + S8
function3(S5678) returns String str3
String output = str1 + Y1+ str2 + Y2 + str3;
This is the whole logic my program.在最后一步中,我对如何调用function3()的循环感到困惑:
for(int i=0; i<Words.length; i++){
if Word[i]= Type1??????????{ doThis(); ?????
//somewhere here I have to call function3(), how the program will judge that the next word is of type2, hence function3 is to be called here.// WHERE AND HOW TO CALL function3();
}
else {doThat();
}对于编程来说,我需要帮助来形成循环的逻辑。
发布于 2014-06-03 18:11:35
我对字符串S12、S34等的多重创建感到困惑。最后,您的结果应该是S12 + Y1+ S34 + Y2 + S5678;。这相当于S1 + S2 + Y1 + S3 + S4 + Y2 + S5 + S6 + S7 + S8。那么,在这里创建这些中间级联有什么意义吗?如果没有,你可以试试这个程序。
编辑:
public class MixProcessor {
private static int counter = 0;
public static void main(String[] args) {
String str= "Wx1 Wx2 Wy1 Wx3 Wx4 Wy2 Wx5 Wx7 Wx8";
StringBuilder output = new StringBuilder();
StringBuilder temp = new StringBuilder();
String previousPatter = "";
boolean shouldMerge = false;
for(String s : str.split(" ")){
String processedString = "";
if (s.matches(".*?x.*")){
shouldMerge = ("x".equals(previousPatter) || previousPatter.trim().length() == 0) ? true : false;
previousPatter = "x";
processedString = function1(s);
} else if (s.matches(".*?y.*")){
shouldMerge = ("y".equals(previousPatter) || previousPatter.trim().length() == 0) ? true : false;
previousPatter = "y";
processedString = function2(s);
}
if(shouldMerge){
temp.append(processedString);
} else {
output.append(function3(temp.toString()));
temp = new StringBuilder(processedString);
}
}
//Append the last value
output.append(function3(temp.toString()));
System.out.println(output.toString());
}
private static String function2(String s) {
return "Y" + s.substring(s.indexOf("y") + 1);
}
private static String function1(String s) {
return "S" + s.substring(s.indexOf("x") + 1);
}
private static String function3(String s) {
// Here this could be any function. I'm just trying to make as per the question
return (s.indexOf("S") != -1) ? ("str" + (++counter)) : s;
}
}https://stackoverflow.com/questions/24021228
复制相似问题