📌  相关文章
📜  给定字符串可能存在的长度为n的子字符串的计数

📅  最后修改于: 2021-05-31 16:45:45             🧑  作者: Mango

给定一个字符串str和一个整数N ,任务是找到长度为N的可能子字符串的数量。
例子:

方法:长度为n的子字符串的计数将始终为len – n + 1 ,其中len是给定字符串的长度。例如,如果str =“geeksforgeeks”n = 5则具有长度5将“爱好者”,“eeksf”的子串的计数,“eksfo”,“ksfor”,“sforg”,“锻造”,“ orgee”,‘rgeek’这是len爱好者’ – N + 1 = 13 – 5 + 1 = 9。
下面是上述方法的实现:

C++
// C++ implementation of the approach
#include 
using namespace std;
 
// Function to return the count of
// possible sub-strings of length n
int countSubStr(string str, int n)
{
    int len = str.length();
    return (len - n + 1);
}
 
// Driver code
int main()
{
    string str = "geeksforgeeks";
    int n = 5;
 
    cout << countSubStr(str, n);
 
    return 0;
}


Java
// Java implementation of the approach
import java.util.*;
 
class GFG
{
 
// Function to return the count of
// possible sub-strings of length n
static int countSubStr(String str, int n)
{
    int len = str.length();
    return (len - n + 1);
}
 
// Driver code
public static void main(String args[])
{
    String str = "geeksforgeeks";
    int n = 5;
 
    System.out.print(countSubStr(str, n));
}
}
 
// This code is contributed by mohit kumar 29


Python3
# Python3 implementation of the approach
 
# Function to return the count of
# possible sub-strings of length n
def countSubStr(string, n) :
 
    length = len(string);
    return (length - n + 1);
 
# Driver code
if __name__ == "__main__" :
 
    string = "geeksforgeeks";
    n = 5;
 
    print(countSubStr(string, n));
     
# This code is contributed by Ryuga


C#
// C# implementation of the approach
using System;
 
class GFG
{
 
// Function to return the count of
// possible sub-strings of length n
static int countSubStr(string str, int n)
{
    int len = str.Length;
    return (len - n + 1);
}
 
// Driver code
public static void Main()
{
    string str = "geeksforgeeks";
    int n = 5;
 
    Console.WriteLine(countSubStr(str, n));
}
}
 
// This code is contributed by Code_Mech.


PHP


Javascript


输出:
9
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”