Dada una string str y un entero N , la tarea es encontrar el número de posibles substrings de longitud N.
Ejemplos:
Entrada: str = “geeksforgeeks”, n = 5
Salida: 9
Todas las substrings posibles de longitud 5 son “geeks”, “eeksf”, “eksfo”, “
ksfor”, “sforg”, “forge”, “orgee” , “rgeek” y “geeks”.
Entrada: str = «jgec», N = 2
Salida: 3
Enfoque: el recuento de substrings de longitud n siempre será len – n + 1 , donde len es la longitud de la string dada. Por ejemplo, si str = «geeksforgeeks» y n = 5 , el recuento de substrings con una longitud de 5 será «geeks» , «eeksf» , «eksfo» , «ksfor» , «sforg» , «forge» , » orgee” , “rgeek” y “geeks” , que es len – n + 1 = 13 – 5 + 1 = 9 .
A continuación se muestra la implementación del enfoque anterior:
C++
// C++ implementation of the approach #include <bits/stdc++.h> 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
<?php // PHP implementation of the approach // Function to return the count of // possible sub-strings of length n function countSubStr($str, $n) { $len = strlen($str); return ($len - $n + 1); } // Driver code $str = "geeksforgeeks"; $n = 5; echo(countSubStr($str, $n)); // This code is contributed by Code_Mech. ?>
Javascript
<script> // JavaScript implementation of the approach // Function to return the count of // possible sub-strings of length n function countSubStr(str, n) { var len = str.length; return len - n + 1; } // Driver code var str = "geeksforgeeks"; var n = 5; document.write(countSubStr(str, n)); </script>
9