📌  相关文章
📜  查找另一个字符串中所有出现的索引

📅  最后修改于: 2021-05-30 11:36:42             🧑  作者: Mango

给定两个字符串str1和str2,任务是打印str1中出现str2的索引(考虑,索引从0开始)。如果没有这样的索引,则打印“ NONE”。

例子:

Input : GeeksforGeeks
        Geeks
Output : 0 8

Input : GFG
        g
Output : NONE

一个简单的解决方案是一一检查给定字符串的所有子字符串。如果子字符串匹配,则打印其索引。

C++
// C++ program to find indices of all
// occurrences of one string in other.
#include 
using namespace std;
void printIndex(string str, string s)
{
  
    bool flag = false;
    for (int i = 0; i < str.length(); i++) {
        if (str.substr(i, s.length()) == s) {
            cout << i << " ";
            flag = true;
        }
    }
  
    if (flag == false)
        cout << "NONE";
}
int main()
{
    string str1 = "GeeksforGeeks";
    string str2 = "Geeks";
    printIndex(str1, str2);
    return 0;
}


Java
// Java program to find indices of all
// occurrences of one String in other.
class GFG {
  
    static void printIndex(String str, String s)
    {
  
        boolean flag = false;
        for (int i = 0; i < str.length() - s.length() + 1; i++) {
            if (str.substring(i, i + s.length()).equals(s)) {
                System.out.print(i + " ");
                flag = true;
            }
        }
  
        if (flag == false) {
            System.out.println("NONE");
        }
    }
  
    // Driver code
    public static void main(String[] args)
    {
        String str1 = "GeeksforGeeks";
        String str2 = "Geeks";
        printIndex(str1, str2);
    }
}
  
// This code is contributed by Rajput-JI


Python3
# Python program to find indices of all
# occurrences of one String in other.
def printIndex(str, s):
  
    flag = False;
    for i in range(len(str)):
        if (str[i:i + len(s)] == s):
              
            print( i, end =" ");
            flag = True;
  
    if (flag == False):
        print("NONE");
          
# Driver code        
str1 = "GeeksforGeeks";
str2 = "Geeks";
printIndex(str1, str2);
  
# This code contributed by PrinciRaj1992


C#
// C# program to find indices of all
// occurrences of one String in other.
using System;
  
class GFG {
  
    static void printIndex(String str, String s)
    {
  
        bool flag = false;
        for (int i = 0; i < str.Length - s.Length + 1; i++) {
            if (str.Substring(i,
                              s.Length)
                    .Equals(s)) {
                Console.Write(i + " ");
                flag = true;
            }
        }
  
        if (flag == false) {
            Console.WriteLine("NONE");
        }
    }
  
    // Driver code
    public static void Main(String[] args)
    {
        String str1 = "GeeksforGeeks";
        String str2 = "Geeks";
        printIndex(str1, str2);
    }
}
  
// This code is contributed by 29AjayKumar


PHP


输出:
0 8

时间复杂度: O(n * n)

一种有效的解决方案是KMP字符串匹配算法。

要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”