我想找到两个字符串的最长公共前缀.
有没有办法循环我的最后几个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
代码应将Welcome作为公共前缀返回.
解决方法:
试试这个.我想这就是你想要实现的目标.如果这是正确的,我会在稍后补充解释
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循环遍历字符串中的每个字符(更多click[1])
>在循环内部,您应该在两个条件下退出
>字符串的结尾(我使用长度来查找是否到达较小的字符串的末尾)
>两个字符串之间不再匹配字符
>你增加索引,直到你在上述某个条件中爆发
>当你退出for循环时,index将包含两个字符串连续相等的最后一个索引.
>如果index = 0.只说不匹配,否则从0开始打印字符直到索引
标签:java,loops,if-statement,string
来源: https://codeday.me/bug/20190517/1120129.html