【发布时间】:2016-09-22 14:27:51
【问题描述】:
这是一道练习题,对我来说比较难。下面是我的静态方法代码(主要方法是固定不变的,并且给出了静态方法的签名),我的目的是获取字符之间的匹配并将它们打印出来。
但也有一些顾虑:
1) 我如何确保当所有字符串都对齐但有多余的字符使布尔值为假并且结果不对齐时不打印? (例如 amgk 作为第二个字符串和第一个字符串是 Java 编程课程)
2) 我如何让它打印正确?目前空格已关闭,字母不是想要的。
3) 如果str1中有多个字符a,我选择放哪个,已经有匹配的怎么省略其余的?
非常感谢能帮助指导像我这样的初学者解决这个问题的伪代码。
public class Q3 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the first string:");
String input1 = sc.nextLine();
System.out.print("Enter the second string:");
String input2 = sc.nextLine();
System.out.println();
if (matchStrings(input1, input2)) {
System.out.println();
System.out.println("There is an alignment as shown above.");
} else {
System.out.println("No alignment can be found.");
}
}
public static boolean matchStrings(String str1, String str2) {
// Modify the code below to return the correct value.
boolean isMatch = false;
//int firstChar = str2.charAt(0);
//int lastChar = str2.charAt(str2.length()-1);
int prevIndex = 0;
System.out.println(str1);
for (int j = 0; j< str2.length(); j++) {
for (int i = 0; i<str1.length();i++) {
char charToSearch = str1.charAt(i);
int newIndex = i;
if (str2.charAt(j)== charToSearch) {
for (int k = prevIndex; k < newIndex-1; k++) {
System.out.print(" ");
}
System.out.print(charToSearch);
//prevIndex=newIndex+1;
isMatch = true;
}
}
}
return isMatch;
}
}
【问题讨论】:
-
从更简单的任务开始
-
如果您需要帮助,您应该在问题中而不是在链接中创建向我们展示您的期望和实际得到的东西。请阅读How do I ask a good question?
-
我认为您没有理解说明。要“对齐”,字符串 1 必须包含字符串 2 中的所有字母,并且顺序相同。也就是说,如果找到第一个字母,那么第二个字母应该在它之后的某个地方,第三个字母应该在它之后的某个地方,等等。 - 所以当字符串 2 包含一个不在字符串 1 中的字母时,就没有“匹配”。
标签: java string loops for-loop indexing