首页 > 解决方案 > 从第二个字符串中的第一个字符串中查找子字符串?

问题描述

更新:我有两个字符串。

  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 的子字符串中搜索该子字符串。如果找到,则返回两者的索引号。然后继续在第二个字符串中找到第一个字符串的第二个子字符串,依此类推直到最后一个。

标签: javastringalgorithmsearchsubstring

解决方案


请在下面找到代码:-

        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}


推荐阅读