I have to write a function in C that counts the occurences of a string "mystring" within an input string.
The user will input a string containing the phrase "mystring" with no spaces anywhere in the string and the program will count how many times "mystring" is read within the input string.
Here is the code I have written so far but it is not working properly.
int substr_count(char *srcString, char *subString)
{
int i = 0; // counter variable
int countOccurence = 0;
while(srcString[i] != 0) // loop until hit a null in srcString
{
if (srcString[i] == subString[i])
{
countOccurence++;
}
i++; // increment to next position in srcString
}
return countOccurence; // return value of occurences
}
int main(void)
{
char srcString[200] = ""; //empty string
char subString[8] = "mystring"; //substring
int get_count = 0;
scanf("%s", srcString); //get a string from input keyboard
get_count = substr_count(srcString, subString);
printf("%s occurs %d times in %s\n", subString, get_count, srcString);
}
Use strstr like this:
#include <stdio.h>
#include <string.h>
int substr_count(const char *srcString, const char *subString){
int countOccurence = 0;
size_t sub_len = strlen(subString);
const char *p = srcString;
while(p = strstr(p, subString)){//if NOT NULL, found it
++countOccurence;
p += sub_len;//set next search point
}
return countOccurence;
}
int main(void){
char srcString[200] = "";
char subString[] = "mystring";//const *char subString = "mystring"
int get_count = 0;
scanf("%199s", srcString);//199 : Set limits
get_count = substr_count(srcString, subString);
printf("%s occurs %d times in %s\n", subString, get_count, srcString);
}
Problems in your code:
Declaring a string or an array?
A string is a contiguous chunk of char with an ending '\\0' null terminator, while an array is a contiguous chunk of element with the same type.
It is very important to know that between string literal (everything between " "
) always have one more element than how it looks.
"haha"
contains 5 chars, 'h', 'a', 'h', 'a', '\\0'
""
contains 1 char, '\\0', even if it looks like empty.
The null terminator charactor do make the difference. all standard string functions will now work if you pass in an array or char.
So you should either declare your subString
as undefined amount of element initialised to "mystring" ( char subString[] = "mystring";
)
or you can declare your subString as an array of 9 elements, with the last element as a null terminator ( char subString[9] = "mystring";
)
your scanf is not defined.
Please include "stdio.h> at the top of the file.
removed due to some mistakes in my answer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.