我想找到两个字符串的最长公共前缀。 有没有办法循环我的最后几个if语句,以便我可以结束彼此不匹配的最后几个字符?
System.out.println("Enter the first string: ");
String s = input.nextLine();
System.out.println("Enter the second string: ");
String s2 = input.nextLine();
//check if first characters are same
if (s.charAt(0) != s2.charAt(0)) {
System.out.println(""+s+ " and "+s2+ " have no common prefix");
System.exit(0);
}
if (s.charAt(0) == s2.charAt(0))
System.out.print(" "+s.charAt(0));
if (s.charAt(0) == s2.charAt(0))
System.out.print(" "+s.charAt(1));
if (s.charAt(0) == s2.charAt(0))
System.out.print(" "+s.charAt(2));
}
}
示例:
Enter first string: Welcome to c++
Enter second string: Welcome to java
代码应返回欢迎使用作为公共前缀。
答案 0 :(得分:3)
可能是这样的:
int sLength = s.length(),
s2Length = s2.length(),
minLength = (sLength < s2Length) ? sLength : s2Length;
for (int i = 0; i < minLength; i++) {
if (s.charAt(i) == s2.charAt(i)) {
System.out.println(s.charAt(i));
}
else {
break;
}
}
但是关于你的问题的更多细节会很棒。
编辑:这取决于@afrojuju_想要做什么。那不清楚。可以添加更多逻辑来实现期望的行为。
编辑2:添加了@JavaBeast指出的字符串长度比较。
答案 1 :(得分:3)
试试这个。我想这就是你想要实现的目标。如果这是正确的,我将在稍后添加解释
import java.util.*;
import java.lang.*;
import java.io.*;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
String s = "Hello Wo";
String s2 = "Hello World";
String small,large;
if(s.length() > s2.length())
{small = s2;large = s;}
else
{small = s;large = s2;}
int index = 0;
for(char c: large.toCharArray())
{
if(index==small.length()) break;
if(c != small.charAt(index)) break;
index++;
}
if(index==0)
System.out.println(""+s+ " and "+s2+ " have no common prefix");
else
System.out.println(large.substring(0,index));
}
}
toCharArray()
将字符串转换为字符,以便您可以使用Java的foreach循环遍历字符串中的每个字符(更多点击[1])index
将包含两个字符串连续相等的最后一个索引。index
答案 2 :(得分:0)
public static String LcpFinder (String s1 , String s2){
if (s1 == null || s2 == null){
throw new IllegalArgumentException();
}
int minLength = 0;
if (s1.length() < s2.length()){
minLength = s1.length();
}
else{
minLength = s2.length();
}
for (int i = 0 ; i < minLength ; i++){
if(s1.charAt(i) == s2.charAt(i)){
continue;
}
else{
return s1.substring(0,i);
}
}
return s1.substring(0,minLength);
}