从第二个字符串的第一个字符串中查找子字符串?

问题描述 投票:-1回答:4

更新:我有两个字符串。

  String a = "is am are has have was " //Helping verbs
  String b= " Robert and william are English Robert has a car he was living in England " //Sentence

更新:从字符串a中选择第一个子字符串,然后在字符串b的子字符串中搜索该子字符串。如果找到,则返回两者的索引号。然后继续在第二个String中找到第一个String的第二个subString,依此类推,直到last。

java string algorithm search substring
4个回答
4
投票
请在下面找到代码:-

String stringA = "one two three four five six " ; String stringB = " eleven two four twelve thirteen "; String[] stringOne = stringA.split(" "); String[] stringTwo = stringB.trim().split(" "); Map<Integer,Integer> mapMatchingStrings = new HashMap<>(); IntStream.range(0,stringOne.length).forEach(indexOfStringOne -> IntStream.range(0,stringTwo.length).forEach(indexOfStringTwo -> { if(Objects.equals(stringOne[indexOfStringOne],stringTwo[indexOfStringTwo])){ mapMatchingStrings.put(indexOfStringOne,indexOfStringTwo); } } )); System.out.println(mapMatchingStrings);

输出:-

{1 = 1,3 = 2}

0
投票
拆分字符串的一种简单方法是使用StringTokenizer类

String a = "one two three four five six"; String b = "eleven two four twelve thirteen"; StringTokenizer aT = new StringTokenizer(a," "/*delimiter(space or comma)*/); while (aT.hasMoreTokens()) { String indexA = aT.nextToken(); StringTokenizer bT = new StringTokenizer(b," "); int index = 0; while(bT.hasMoreTokens()) { if(bT.nextToken().equals(indexA))System.out.println("Found Match:"+index); index++; } }


0
投票
String a = "one two three four five six "; String b= " eleven two four twelve thirteen " ; List<String> aSub = Arrays.asList(a.split(" ")); List<String> bSub = Arrays.asList(b.split(" ")); for(String s1 :aSub){ for(String s2 :bSub){ if(s1.equalsIgnoreCase(s2)){ System.out.println( s1+" exists and is found in index "+ bSub.indexOf(s1)); } } }
结果:

存在两个并且在索引2中找到

存在四个并且在索引3中找到


0
投票
//Big O of N*N solution class SubString{ public static void main(String [] args) { System.out.println(new SubString().getCommonSubString("abcdefg","zycdemm")); } public int getCommonSubString(String A, String B) { int ans =0; for(int i=0;i<A.length();i++) { int c=0; int k =i; for(int j=0;k<A.length()&&j<B.length();j++) { if(A.charAt(k)==B.charAt(j)) { c++; ans = Math.max(ans, c); k++; }else { c=0; k=i; } } } return ans; } }
© www.soinside.com 2019 - 2024. All rights reserved.