I use the following KMP algorithm code for string matching. Its works fine to search a given pattern in the string.
/*
* C Program to Implement the KMP Pattern Searching Algorithm
*/
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
char string[100], matchcase[20], c;
int i = 0, j = 0, index;
printf("Declertion and Initialization done:\n");
/*Scanning string*/
printf("Enter string:");
do
{
fflush(stdin);
c = getchar();
string[i++] = tolower(c);
} while (c != '\n');
string[i - 1] = '\0';
printf("The string after scanning is:%s\n",string);
printf("String length of string is: %d\n",strlen(string));
/*Scanning substring*/
printf("Enter substring: ");
i = 0;
do
{
fflush(stdin);
c = getchar();
matchcase[i++] = tolower(c);
} while (c != '\n');
matchcase[i - 1] = '\0';
for (i = 0; i < strlen(string) - strlen(matchcase) + 1; i++)
{
index = i;
if (string[i] == matchcase[j])
{
do
{
i++;
j++;
} while(j != strlen(matchcase) && string[i] == matchcase[j]);
if (j == strlen(matchcase))
{
printf("Match found from position %d to %d.\n", index + 1, i);
return 0;
}
else
{
i = index + 1;
j = 0;
}
}
}
printf("No substring match found in the string.\n");
return 0;
}
It searches the pattern successfully,giving the first match only,however ,i am interested to report all the matches. Thanks
Related
I was trying this pattern matching method in C but whenever I give all the input, the vscode terminal waits for a while and just stops the program without any warnings/message. Can anyone point to what is wrong here?
#include <stdio.h>
#include <string.h>
int main()
{
char STR[100], PAT[100], REP[100], ANS[100];
int i, m, j, k, flag, slP, slR, len;
i = m = k = j = flag = len = 0;
printf("\nMain String: ");
gets(STR);
printf("\nPattern String: ");
gets(PAT);
slP = strlen(PAT);
printf("\nReplace String: ");
gets(REP);
slR = strlen(REP);
while (STR[i] != '\0')
{
if (STR[i] = PAT[j])
{
len = 0;
for (k = 0; k < slP; k++)
{
if (STR[k] = PAT[k])
len++;
}
if (len == slP)
{
flag = 1;
for (k = 0; k < slR; k++, m++)
ANS[m] = REP[k];
}
}
else
{
ANS[m] = STR[i];
m++;
i++;
}
}
if (flag == 0)
{
printf("\nPattern not found!");
}
else
{
ANS[m] = '\0';
printf("\nResultant String: %s\n", ANS);
}
return 0;
}
There are multiple problems in the code:
using gets() is risky, this function was removed from the C Standard because it cannot be used safely.
if (STR[i] = PAT[j]) copied the pattern to the string. You should use:
if (STR[i] == PAT[j])
similarly, if (STR[k] = PAT[k]) is incorrect. You should compare PAT[k] and STR[i + k]:
if (STR[i + k] == PAT[k])
you should test for buffer overflow for the output string as replacing a short string by a larger one may produce a string that will not fit in ANS
you do not increment i properly.
Here is a modified version:
#include <stdio.h>
int getstr(const char *prompt, char *dest, int size) {
int c, len = 0;
printf("%s", prompt);
while ((c = getchar()) != EOF && c != '\n') {
if (len + 1 < size)
dest[len++] = c;
}
if (size > 0)
dest[len] = '\0';
printf("\n");
if (c == EOF && len == 0)
return -1;
else
return len;
}
int main() {
char STR[100], PAT[100], REP[100], ANS[100];
int i, m, k, flag;
if (getstr("Main String: ", STR, sizeof STR) < 0)
return 1;
if (getstr("Pattern String: ", PAT, sizeof PAT) < 0)
return 1;
if (getstr("Replace String: ", REP, sizeof REP) < 0)
return 1;
i = m = flag = 0;
while (STR[i] != '\0') {
if (STR[i] == PAT[0]) { // initial match
// compare the rest of the pattern
for (k = 1; PAT[k] != '\0' && PAT[k] == STR[i + k]; k++)
continue;
if (PAT[k] == '\0') { // complete match
flag = 1;
// copy the replacement string
for (k = 0; REP[k] != '\0'; k++) {
if (m + 1 < sizeof ANS)
ANS[m++] = REP[k];
}
i += k; // skip the matching characters
continue;
}
}
// otherwise copy a single character
if (m + 1 < sizeof ANS)
ANS[m++] = STR[i];
i++;
}
ANS[m] = '\0';
if (flag == 0) {
printf("Pattern not found!\n");
} else {
printf("Resultant String: %s\n", ANS);
}
return 0;
}
I tried modifying this code to print
no solution
if there is no input by user. That is, if I run the program and simply press enter it should print no solution. I added the code that's meant to do that to check if the string length is 0 then print but it doesn't work
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10];
int i, j, ctr;
fgets(str1, sizeof str1, stdin);
j = 0; ctr = 0;
if (strlen(str1) == 0) {
printf_s("no solution");
}
else
for (i = 0; i <= (strlen(str1)); i++)
{
// if space or NULL found, assign NULL into newString[ctr]
if (str1[i] == ' ' || str1[i] == '\0')
{
newString[ctr][j] = '\0';
ctr++; //for next word
j = 0; //for next word, init index to 0
}
else if (str1[i] == '.' || str1[i] == ',')
{
newString[ctr][j] = '\0';
ctr--; //for next word
j = - 1;
}
else
{
newString[ctr][j] = str1[i];
j++;
}
}
printf("\n\n");
for (i = 0; i < ctr; i++)
printf(" %s\n", newString[i]);
return 0;
}
fgets() will add a new line to your string (see this link for more information) which means when you simply press enter your string length(since your string includes \n) is 1 , you should say:
if (strlen(str1) == 1) {
printf_s("no solution");
// it's better to add a return 0; here if you don't want to continue the program
}
or use this instead:
if (!strcmp(str1,"\n")) {
printf_s("no solution");
}
I have school task. To reverse each word in sentence, so example :
Input: Fried chicken, fried duck.
Output: deirF nekcihc, deirf kcud.
So except dot and comma it's not reversed.
The first code
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main() {
int i, n, titik = 0, coma = 0;
char s[5001];
char c[5001];
char *tok;
scanf("%[^\n]s", s);
if (s[0] == ' ')
printf(" ");
tok = strtok(s, " ");
while (tok != NULL) {
strcpy(c, tok);
n = strlen(c);
for (i = n; i >= 0; i--) {
if (c[i] == ',') {
coma = 1;
} else
if (c[i] == '.') {
titik = 1;
} else
printf("%c", c[i]);
}
if (coma) {
printf(",");
coma = 0;
} else
if (titik){
printf(".");
titik = 0;
}
tok = strtok(NULL," ");
if (tok == NULL)
printf("\n");
else
printf(" ");
}
}
Second code is
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
int i, j, n, prana = 0, titik = 0, coma = 0, end = 0;
char s[5001];
scanf("%[^\n]s", s);
n = strlen(s);
for (i = 0; i <= n; i++) {
if (isspace(s[i]) || iscntrl(s[i])) {
if (iscntrl(s[i]))
end = 1;
for (j = i - 1; j >= prana; j--) {
if (s[j] == '.') {
titik = 1;
} else
if (s[j] == ',') {
coma = 1;
} else
printf("%c", s[j]);
}
prana = i + 1;
if (titik) {
titik = 0;
if (end)
printf(".");
else
printf(". ");
} else
if (coma) {
coma = 0;
if (end)
printf(",");
else
printf(", ");
} else {
if (end)
printf("");
else
printf(" ");
}
}
}
printf("\n");
return 0;
}
Why the second code is accepted in test case?, but first code is not.
I tested the result it's same. Really identical in md5 hash.
The output of the two codes id different, because you print the terminating null character for each token in the first code. This loop:
for (i = n; i >=0 ; i--) ...
will have i == n in its first iteration. For a C string of length n, s[n] is the terminating null. This character may not show in the console, but it is part of the output.
To fix the loop, you could start with i = n - 1, but C uses inclusive lower bounds and exclusive upper bounds, and a more idomatic loop syntax is:
i = n;
while (i-- > 0) ...
Not related to your question at hand, but your codes are rather complicated, because they rely on many assumptions: words separated by spaces; only punctuation is comma or stop; repeated punctuation marks are ignored, special case for last word.
Here's a solution that treats all chunks of alphabetic characters plus the apostrophe as words and reverses them in place:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
void reverse(char *str, int i, int j)
{
while (i < j) {
int c = str[--j];
str[j] = str[i];
str[i++] = c;
}
}
int main()
{
char str[512];
int begin = -1;
int i;
if (fgets(str, sizeof(str), stdin) == NULL) return -1;
for (i = 0; str[i]; i++) {
if (isalpha((unsigned char) str[i]) || str[i] == '\'') {
if (begin == -1) begin = i;
} else {
if (begin != -1) {
reverse(str, begin, i);
begin = -1;
}
}
}
printf("%s", str);
return 0;
}
I'm trying to print the longest word in string but the loop is not running, I couldn't find a solution for this one.
char str[50];
int i = 0, count = 0, numOfWords = 0, place;
printf("Please enter a sentence: ");
gets(str);
while (str[i] != '\0') {
if (str[i] != ' ') {
numOfWords++;
if (str[i + 1] == ' ') {
if (numOfWords > count) {
count = numOfWords;
place = i + 1 - numOfWords;
numOfWords = 0;
}
}
}
i++;
}
puts(str);
printf("%d", count);
printf("The word is:\n");
for (i = place; i < numOfWords; i++)
printf("%c\n", str[i]);
getch();
You should use count to determine how many times the last loop should be taken.
You should also process the last word.
Try this:
#include <stdio.h>
#include <string.h>
/* This implementation is simple, but maximum readable length is decreased by 1 */
char* safer_gets(char* s, size_t max){
char* lf;
if (fgets(s, max, stdin) == NULL) return NULL;
if ((lf = strchr(s, '\n')) != NULL) *lf = '\0'; /* remove the newline character */
return s;
}
int main(void){
char str[51];
int i = 0, count = 0, numOfWords = 0, place = 0;
printf("Please enter a sentence: ");
safer_gets(str, sizeof(str));
while (str[i] != '\0')
{
if (str[i] != ' ')
{
numOfWords++;
if (str[i + 1] == ' ' || str[i + 1] == '\0')
{
if (numOfWords > count)
{
count = numOfWords;
place = i +1- numOfWords;
numOfWords = 0;
}
}
}
i++;
}
puts(str);
printf("%d", count);
printf("The word is:\n");
for (i = 0; i < count; i++)
printf("%c", str[place + i]);
putchar('\n');
return 0;
}
I have been stuck on this for a while now. I wrote my program to count word occurrence in an inputted string by the user as well to sort the words alphabetically. My issue is my program runs perfectly only if there are spaces in between the words inputted. For example, if I input "to to," my program will count those two words as two different words due to the comma rather than counting it as one word in "to" as I would like it to. It is that issue for all of my delimiters in the array const char delim[]. How can I fix this issue in my program? I really appreciate any help! My code is down below:
Edit: I took Bob's suggestion to use strchr() and it worked! My only issue is my program outputs the count for delimiters now. I was thinking of possibly writing an if statement when comparing words[i] with words[j] to see if they have the same value. Is that the best approach to it?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
const char delim[] = ", . - !*()&^%$##<> ? []{}\\ / \"";
#define SIZE 1000
int main(){
char string[SIZE], words[SIZE][SIZE], temp[SIZE];
int a = 0, i = 0, j = 0, k = 0, n = 0, count;
int c = 0, cnt[26] = { 0 };
int word = 0;
int x;
printf("Enter your input string:");
fgets(string, SIZE, stdin);
string[strlen(string) - 1] = '\0';
lower(string);
/*extracting each and every string and copying to a different place */
while (string[i] != '\0'){
if (strchr(", . - !*()&^%$##<> ? []{}\\ / \"", string[i]) != NULL){
words[j][k] = '\0';
k = 0;
j++;
}else {
words[j][k++] = string[i];
}
i++;
}
words[j][k] = '\0';
n = j;
printf("Number of occurences of each word unsorted:\n");
i = 0;
/* find the frequency of each word and print the results */
while (i <= n) {
count = 1;
if (i != n) {
for (j = i + 1; j <= n; j++) {
if (strcmp(words[i], words[j]) == 0) {
count++;
for (a = j; a <= n; a++)
strcpy(words[a], words[a + 1]);
n--;
}
}//for
}
//word == strtok(string, delim);
/* count - indicates the frequecy of word[i] */
printf("%s\t%d\n", words[i], count);
i = i + 1;
}//while
printf("Alphabetical Order:\n");
/* sort the words in the given string */
for (i = 0; i < n; i++){
strcpy(temp, words[i]);
for (j = i + 1; j <= n; j++){
if (strcmp(words[i], words[j]) > 0){
strcpy(temp, words[j]);
strcpy(words[j], words[i]);
strcpy(words[i], temp);
}
} //inner for
} //outer for
i = 0;
while (i <= n) {
count = 1;
if (i != n) {
for (j = i + 1; j <= n; j++) {
if (strcmp(words[i], words[j]) == 0) {
count++;
}
}
}
printf("%s\n", words[i]);
i = i + count;
}
}
Strip every word of that delimeter before comparing. Actually you don't even need a list of delimeters because words are 'alpha' other than that it's a delimeter.
Please try this, it works, it is an extract of your own code, a little bit modified, it will give you the count, then you have to write the rest, have fun.
#include <string.h>
#define YES 1
#define NO 0
int main( )
{
char string[1000];
int i = 0;
int j = 0;
int is_this_a_word = 0;
strcpy( string, " to or not ,tobe" );
while ( string[i++] != '\0' )
{
if ( strchr( ", . - !*()&^%$##<> ? []{}\\ / \"", string[i] ) != NULL )
{
is_this_a_word = NO;
}
else
{
if ( ! is_this_a_word )
{
is_this_a_word = YES;
j++;
}
}
}
printf( "I counted %d words", j );
getchar( );
}