C++中给定字符串长度为n的子字符串计数
给定一个字符串str[]和一个数字n。目标是找到str[]中所有长度为n的子字符串。如果字符串是“abcde”并且n=3,则长度为3的子字符串是“abc”、“bcd”、“cde”,计数为3。
让我们通过例子来理解。
输入 − str[] = “computer” n=4
输出 − 给定字符串中长度为n的子字符串个数为:5
说明 − 长度为4的子字符串为:“comp”,“ompu”,“mput”,“pute”,“uter”
输入 − str[] = “development” n=5
输出 − 给定字符串中长度为n的子字符串个数为:7
说明 − 长度为5的子字符串为:“devel”,“evelo”,“velop”,“elopm”,“lopme”,“opmen”,“pment”。
下面程序中使用的方法如下
如果我们将字符串str[]的长度作为L,则str[]内长度为n的子字符串的个数为L-n+1。如果字符串是“abcdefghi”并且n是4,则子字符串将是“abcd”,“bcde”,“cdef”,“defg”,“efgh”,“fghi”。个数是6。同时9-4+1=6。
取一个字符串str。
取n为整数。
函数possible_substring(string str, int length, int n)接受一个字符串、它的长度n并返回str中长度为n的子字符串的个数。
取一个变量count。
设置count = length-n+1。
最后返回count作为结果。
示例
#include <bits/stdc++.h>
using namespace std;
int possible_substring(string str, int length, int n){
int count = length - n + 1;
return count;
}
int main(){
string str = "learning";
int length = str.length();
int n = 2;
cout<<"Count of substrings of length n possible from the given string are: "<<possible_substring(str, length, n);
return 0;
}输出
如果我们运行上面的代码,它将生成以下输出:
Count of substrings of length n possible from the given string are: 7
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP