C find exact word in string - c

How to find exact words in string in C? Example:
word to find: "cat"
string: "cats dog" result nothing
string "cat dog" result found word "cat"

first you can use strtok function to split string into separate word and then use strcmp to comapre the result words againts your interest word.
#include <stdio.h>
#include <string.h>
int main() {
char string[50] = "cats dog";
char *token = strtok(string, " "); // split string by space
// here token contains one word in string
// each time strtok(NULL, " ") is called, the next word will be extracted
while( token != NULL ) {
printf( " %s\n", token ); //printing each token
if (!strcmp(token, "cat"))
{
printf("cat found!\n");
}
token = strtok(NULL, " ");
}
return 0;
}

Related

How can i print the whole sentence without punctuations? [duplicate]

This question already has answers here:
Using strtok in c
(7 answers)
Closed 3 years ago.
I couldn't print the whole output in a string.
All I know is that %s should work like a loop
for example
printf("%s", str);
works the same as puts(str);
#include <stdio.h>
#include <string.h>
int main (){
char str[]="Hello:, student; how are you? This task is easy!";
char *token;
char del[] = ", ; : ? !", cp[80];
int count;
strcpy(cp, str);
token = strtok(str, del);
count = 0;
while( token != NULL )
{
printf("%s\n", token);
token = strtok(NULL, del);
count++;
}
strtok(str, del);
printf("Your sentence has %d words\n", count);
puts("The sentence without punctuation charachters is: \n ");
puts(str); // This should where it show me the output
return 0 ;
}
// I tried to follow the instruction I had to write this code in this form.
// This is the output that I suppose to get
Hello
student
how
are
you
This
task
is
easy
Your sentence has 11 words
The sentence without punctuation characters is:
Hello student how are you This task is easy
// all I got is ( ignore the extra line between each word)
Hello
student
how
are
you
This
task
is
easy
Your sentence has 11 words
The sentence without punctuation characters is:
Hello
strtok(str, del); modifies its first parameter adding null characters inside, this is why when you print str after the calls of strtok you got only the first token
you save the string doing strcpy(cp, str); but you do not use it, and you also hope 80 is enough ...
A proposal placing the words in cp then printing it :
#include <stdio.h>
#include <string.h>
int main (){
char str[]="Hello:, student; how are you? This task is easy!";
char *token;
char del[] = ", ; : ? !", cp[sizeof(str) + 1];
int count;
size_t pos = 0;
token = strtok(str, del);
count = 0;
while( token != NULL )
{
printf("%s\n", token);
strcpy(cp + pos, token);
pos += strlen(token);
cp[pos++] = ' ';
token = strtok(NULL, del);
count++;
}
cp[(pos == 0) ? 0 : (pos - 1)] = 0;
printf("Your sentence has %d words\n", count);
puts("The sentence without punctuation characters is:");
puts(cp); // This should where it show me the output
return 0 ;
}
Compilation and execution :
pi#raspberrypi:/tmp $ gcc -pedantic -Wall -Wextra c.c
pi#raspberrypi:/tmp $ ./a.out
Hello
student
how
are
you
This
task
is
easy
Your sentence has 9 words
The sentence without punctuation characters is:
Hello student how are you This task is easy
pi#raspberrypi:/tmp $

How to print a word with specific character in C?

Sample Input: Stack Overflow is Awesome
Character to Search: e
Output: Overflow Awesome
I wrote a code to split a string by space and store as words but i don't know how to check and print the result
#include <stdio.h>
#include <string.h>
int main()
{
char str1[100];
char newString[10][10];
int i,j,ctr;
printf("\n\n Split string by space into words :\n");
printf("---------------------------------------\n");
printf(" Input a string : ");
fgets(str1, sizeof str1, stdin);
j=0; ctr=0;
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
{
newString[ctr][j]=str1[i];
j++;
}
}
printf("\n Strings or words after split by space are :\n");
for(i=0;i < ctr;i++)
printf(" %s\n",newString[i]);
return 0;
}
You can use strchr() to easily check a string for a specific chararacter
for (i = 0; i < ctr; i++) {
if (strchr(newString[i], 'e') != NULL) {
printf(" %s\n", newString[i]);
}
}
Add the following lines at end to your code to print the filtered strings/words by character e
printf("\n Strings or words Containing character 'e' :\n");
for(i=0;i < ctr;i++)
if(strchr(newString[i], 'e') != NULL)
printf(" %s\n",newString[i]);
Since you are parsing str1 in order to find the beginning and the end of each word, why not using the for loop to detect if the current word contain the letter that you search ?
There are many little "error" too : do not use "strlen" in the for loop, it will be call each time ! Instead, detect '\0' !
Your result array newString is unsafe ! It should be [50][100] because you can input a string of one word with 100 char ( so [1][100] ) or 50 letter and 50 blank (so [50][2] ). So the result array must be [50][100] in order to take any possibility.
I would suggest to split the string using the strtok and using the strchr to check if the substring contains the letter e. In this way you can loop a single time over the original string and perform both the splitting and the checking.
Something like this:
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] ="Stack Overflow is Awesome";
char* pch;
char* pch2;
//split string by spaces
pch = strtok (str," ");
while (pch != NULL)
{
//check if the substring contains the letter 'e'
pch2 = strchr(pch,'e');
if (pch2 != NULL) {
printf ("%s\n",pch);
}
pch = strtok (NULL, " ");
}
return 0;
}

How to seperate user input word delimiter as space using strtok

Why am I getting a segmentation fault after only reading one word?
If I enter "why is this not work"
I only get back
why
and then I get a segmentation fault.
I've seen other examples but none have used user input like I am trying to do here. I can only read one word and it won't work. I tried changing all the %c to %s but it is not helping me. I also realize segmentation fault is pointer pointing to somewhere not in memory but I cannot see what is wrong with it. Please help me understand.
#include <stdio.h>
#include <string.h>
int main()
{
char word[100];
printf("Enter a sentence: ");
scanf("%s", word);
char *tok = strtok(word, " ");
printf("%s\n", tok);
while(tok != NULL)
{
tok = strtok(NULL, " ");
printf("%s\n", tok);
if(tok == NULL)
printf("finished\n");
}
return 0;
}
EDIT: I changed scanf("%s", word); to fgets(word, 100, stdin); and now it prints everything but I get a Segmentation fault.
As pointed in comments, there is at least two problems in your first code.
Do not use scanf to read a string that you want to parse. Use fgets instead.
You do not test that tok is not NULL before using it (inside the while loop)
Such problems would have been easily detected with debugging, so I encourage you to read how to debug small programs
Corrected code should be like:
#include <stdio.h>
#include <string.h>
int main(void)
{
char word[100];
printf("Enter a sentence: ");
/* read from stdin
note the `sizeof char`, if you need to change the size of `word`,
you won't have to change this line. */
fgets(word, sizeof word, stdin);
/* initialize parser */
char *tok = strtok(word, " ");
while (tok != NULL)
{
/* printf token: it cannot be NULL here */
printf("%s\n", tok);
/* get next token*/
tok = strtok(NULL, " ");
}
printf("finished\n");
return 0;
}
This code is not correct
while(tok != NULL)
{
tok = strtok(NULL, " ");
printf("%s\n", tok);
if(tok == NULL)
printf("finished\n");
}
suppose you get to the last pass through the loop.... it gets into the loop as you got last time.... so you make a tok = strtok(NULL, " "); which returns (and assigns) NULL as there is no more stuff.... then you printf(3) it, which produced the seg fault.
Just change that into this, so you don't enter into the loop if no more tokens are available.
while((tok = strtok(NULL, " ")) != NULL)
{
printf("%s\n", tok);
/* you don't touch tok inside the loop, so you don't need to
* test it again once you get inside */
}
/* if(tok == NULL) <-- you always have tok == NULL here */
printf("finished\n");
or simpler
while(tok = strtok(NULL, " "))
{
printf("%s\n", tok);
}
printf("finished\n");
Also, add \n to the second parameter of strtok(3) call (in the two calls you have in your listing, as you can have only one token, and the final line ending has to be dropped from the first call), as when you use fgets(3) you normally will get a \n at the end of the string (which you don't want):
char *tok = strtok(word, " \n");
printf("%s\n", tok);
while(tok = strtok(NULL, " \n"))
{
printf("%s\n", tok);
}
printf("finished\n");

Taking a string, and parsing/tokenizing into smaller strings using hyphen delimiter

I am tasked with writing a C program that will take a string with hyphens in it, and check to see that the first group of the string (before the hyphen) is alphabet/letter only, the next group is numeric only, and the last group is alphabet/letter only. It is similar to this project: http://wps.aw.com/wps/media/objects/7257/7431666/Case_Studies/GaddisJavaCSO_CS6.pdf
So far I am stuck on splitting the string into 3 variables. I have read about strtok and manipulating the scanf function, but I haven't been successful:
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char serial [50];
char * part1 = NULL, part2 = NULL, part3 = NULL;
printf("Enter Serial Number:\n");
scanf("%s", serial);
part1 = strtok (serial, "-");
part2 = strtok(NULL, "-");
part3 = strtok(NULL, "-");
printf("You entered %s\n", part1);
printf("You entered %s\n", part2);
printf("You entered %s\n", part3);
return 0;
}
you are using strtok wrong, pass parameters to it and it should work fine.
char * pch = strtok (serial, "-" );
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, "-");
}
or in your example you need to define each as a char* :
char * part1= strtok (serial, "-");
char * part2 = strtok(NULL, "-");
char* part3 = strtok(NULL, "-")
StrTok + example
strcpy(part1, strtok(serial, "-"));//premise: string has hyphen
strcpy(part2, strtok(NULL, "-"));
strcpy(part3, strtok(NULL, "-"));
You could utilize scanf's formatting rules to read your strings directly from the input line.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main ()
{
char part1[40], part2[40], part3[40];
int count, n;
do{
n = 0;
flushall();
printf("Enter Serial Number:\n");
count = scanf(" %39[A-Za-z]-%39[0-9]-%39[A-Za-z]%n", part1, part2, part3, &n);
if( count != 3 || n == 0 ){
printf("Recognize %i parts, %s\n", count, n == 0 ? "did not parse to the end" : "parsed to the end");
}
}while(count != 3 || n == 0);
printf("You entered %s\n", part1);
printf("You entered %s\n", part2);
printf("You entered %s\n", part3);
return 0;
}
This is quite a strict form of parsing the input and requires the user to keep the outer form. You can easily filter allowed strings by not using %s but rather something like %[0-9]. The best way for me to filter serialnumber inputs was always Regex if available... but i dont think this is part of your homework yet :)

strtok return string?

just having a little issue with strtok and strcmp.
I'm trying to compare the input of a user via fgets to some predetermined string:
char *token[100];
fgets(s, sizeof(s), stdin)
token[0] = strtok(s, " "); // Get first word
printf("tok: %s", token[0]);
printf("cmp: %d\n", strcmp(token[0], "/bin/echo");
Obviously it's not all the code but this shows my problem - if I enter "/bin/echo ..." (or anything for that matter), it will be put into token[0], and get printed. It prints correctly but when it prints the cmp value it's never 0. For /bin/echo, the cmp value is 1 for some reason.
Thanks.
EDIT to clear up confusion about s and token:
char s[1024];
char *token[100];
EDIT 2 - Added some other test cases:
I entered "/bin/echo hello world" to stdin
token[0] = strtok(s, " \n\0"); // Get first word
printf("token[0] is: %s", token[0]);
printf("cmp: %d\n", strcmp(token[0], "/bin/echo"));
Output:
token[0] is: /bin/echo
cmp: 1
And then I tried hardcoding the tokened string:
char str[] = "/bin/echo hello world";
token[0] = strtok(str, " ");
printf("token[0] is: %s", token[0]);
printf("cmp: %d\n", strcmp(token[0], "/bin/echo"));
Output:
token[0] is: /bin/echo
cmp: 0
here i have made small program
#include<string.h>
#include<stdio.h>
int main()
{
char str[] ="/bin/echo this is something";
char * token[100];
token[0] = strtok (str," ");
token[0] = strtok(str, " "); // Get first word
printf("cmp: %d\n", strcmp(token[0], "/bin/echo"));
return 0;
}
Here i have statically stored input string instead of fgets()
That works fine.
see http://codepad.org/IrGAXT8f
Use
char token[1000];
strcpy(token,strtok(s," "));
string's can't be assigned directly like this in c :)
also, include string.h
One needs to allocate memory dynamically for copying strings. Read about dynamic memory management first (malloc, calloc, etc...)
EDIT:
http://ideone.com/0UxEwO - works for me
#include <stdio.h>
#include <string.h>
int main()
{
char s[1024];
char *token[100];
fgets(s, sizeof(s), stdin);
token[0] = strtok(s, " \n\0");
printf("token[0] is: %s", token[0]);
printf("cmp: %d\n", strcmp(token[0], "/bin/echo"));
}

Resources