C++字符串中找一对字母出现的次数

来源:百度知道 编辑:UC知道 时间:2024/06/02 21:35:32
两种方式,一种用string,另一种用char数组,例如:
字符"ab"在"xabaacbaxabb"中出现两次

string的
#include <string>
#include <iostream>
using namespace std;
main()
{
string A,B;
cin >>A>>B;
int n,s=0,time=0;
while((n=A.find(B,s))!=-1)s=n+1,time++;
cout <<time<<endl;
}

char的
#include <stdio.h>
#include <string.h>
main()
{
char A[50],B[3],i=0,len,time=0;
scanf("%49s%2s",A,B);
len=strlen(A);
while(i<len)if(!strncmp(A+i++,B,2))time++;
printf("%d",time);
}

//以下均通过 Microsoft Studio 2008 Pro. 运行。
//更改有关字符串的值,程序依然正确。

//====char====
#include<iostream>
#include<string>
using namespace std;

int main()
{
char * child = "ab";
char * parent = "xabaacbaxabb";
int counter = 0;
for( size_t index = 0; index < strlen(parent); ++index )
{
if( !strncmp( parent+index, child, strlen(chil