计算char sir2在序列sir1 []中出现的次数

时间:2015-10-28 16:43:14

标签: c

我对某些字符有疑问,我无法弄清楚如何解决它。给出了一系列字符串和另一个字符串。我必须计算字符串序列中字符串的出现次数。我做了下面的程序,但它没有用。

的main.cpp

#include "tipulbool.h"
char sir1[25], sir2;
int n, i, k;
int main (){
    cin>>n;
    for(i = 1; i <= n; i++)
        cin>>sir1[i];
    cin>>sir2;
    for(i = 1; i <= n; i++)
        k += secventa(sir1[i], sir2);
    cout<<k;
    return 0;
}

tipulbool.h

#include <iostream>
#include <string.h>
using namespace std;


int secventa (char sir1[], char sir2);

tipulbool.cpp

#include "tipulbool.h"

int secventa (char sir1[], char sir2){
    int contor;
    char *p;
    p = strstr(sir1[], sir2);
    if(p)
        contor++;
    while(p){
        p = strstr(p + 1, sir2);
        if(p)
            contor++;
    }
    return contor;
}

2 个答案:

答案 0 :(得分:0)

试试这个:

int countOfChars(char sir1[], char sir2)
{
   int count = 0;
   char* p = sir1;
   while (*p)
   {
       if (p == sir2)
       {
           ++count;
       }
       ++p;
   }
   return count;
}

答案 1 :(得分:0)

此代码:

#include "tipulbool.h"

int secventa (char sir1[], char sir2){
    int contor;
    char *p;
    p = strstr(sir1[], sir2);
    if(p)
        contor++;
    while(p){
        p = strstr(p + 1, sir2);
        if(p)
            contor++;
    }
    return contor;
}

自我迷失。

建议:

#include "tipulbool.h"

int secventa (char sir1[], char sir2){
    int contor = 0;
    char *p = str1;

    while(NULL != (p = strchr(p, str2) ) )
    {
            contor++;
            p++;
    }
    return contor;
}

但请注意

1) I used `strchr()` rather than `strstr()` 
   because `str2` is a single char, not a string
2) I removed the repetitive code
3) `str1` MUST be a NULL terminated string, which in the posted code is not the case.  

关于此代码:

#include "tipulbool.h"
char sir1[25], sir2;
int n, i, k;
int main (){
    cin>>n;
    for(i = 1; i <= n; i++)
        cin>>sir1[i];
    cin>>sir2;
    for(i = 1; i <= n; i++)
        k += secventa(sir1[i], sir2);
    cout<<k;
    return 0;
}

在C ++中,数组偏移量从0开始并继续(数组-1的长度)

仅在单个函数中使用的变量应该(通常)在该函数中定义为局部/自动变量。

建议使用类似以下的代码:

#include "tipulbool.h"

int main ( void )
{
    char sir2;

    int n;      // will contain number of char in str1
    int i;      // loop counter
    int k = 0;  // will contain number of occurrence of str2 in str1

    // get count of chars in first string
    cin >> n;

    // allocate room for first string (using C string)
    // +1 to allow for NUL terminator byte
    char *sir1 = new char[n+1];

    // initialize first string
    memset( sir1, 0x00, n+1 );

    // input first string
    for(i = 0; i < n; i++)
        cin >> sir1[i];

    // input target char
    cin >> sir2;

    // get count of occurances of str2 in str1
    k = secventa(sir1, sir2);

    cout << k << endl;

    delete [] str1;
    return 0;
}

由于这是C ++,您可能需要查看vectorstring 进一步简化代码的书面部分