c++基础题
输入两个字符串s和t,打印出t在s中的出现的位置,并输出出现的次数如输入:s=qwqwertqweqqqq,t=qw
这个怎么写?
[解决办法]
#include<stdio.h>#include<string.h>int main(){ char s[128],t[128]; char *pTemp; int nLenS,nLenT,nCount=0; memset(s, 0, sizeof(s)); memset(t, 0, sizeof(t)); printf("please input s :\n"); scanf("%s", s); printf("please input t :\n"); scanf("%s", t); nLenS = strlen(s); nLenT = strlen(t); pTemp = s; while(1) { if(strstr(pTemp,t) != NULL) { nCount++; pTemp = strstr(pTemp,t) + nLenT; } else { break; } } printf("the times : %d", nCount); return 0;}
[解决办法]
这个可以直接运行:
#include <iostream>using std::cout;using std::endl; int main(){ const char *s = "qwqwertqweqqqq"; const char *target = "qw"; int j,k,count = 0,position[20]; for(int i = 0;s[i] != '\0'; ++i) { for(j=0,k = i;target[j] != '\0';++j,++k) { if(s[k] != target[j]) break; } if(target[j] == '\0') { position[count] = i + 1; ++count; } } cout << "总共出现的次数:" << count << endl; cout << "出现的位置:" ; for(int i = 0; i < count; ++i) { cout << position[i] << " "; } cout << endl; return 0;}
[解决办法]
bool outPut(char *str1,char *str2)
{
assert(str1 && str2);
assert(strlen(str1)>strlen(str2));
char* ch1=str1;
char* ch2=str2;
int i=0;
int count=0;
while(*ch1)
{
if(!*ch2)
{
cout<<i-strlen(str2)<<" ";
ch2=str2;
count++;
}
if(*ch1==*ch2)
{
ch1++;
ch2++;
}
else
ch1++;
i++;
}
cout<<endl;
cout<<" 次数:"<<count;
}