Finding a substring, using pointers - c

As the title mention, I want to check if a substring is found or not into another string.
#include <stdio.h>
#include <stdlib.h>
int isIncluded(char *text, char* pattern);
int main()
{
char text[30];
char pattern[30]; int result;
printf(" Please introduce your text \n");
scanf("%s", &text);
printf(" Please introduce the pattern you are looking for \n");
scanf("%s", &pattern);
result = isIncluded( &text, &pattern);
if ( result == 1)
{
printf(" Your pattern has been found in your text \n " ) ;
}
if ( result == 0)
{
printf(" no substring found \n " ) ;
}
}
int isIncluded(char *text, char* pattern)
{
int ct = 0;
int numberofcharacters = 0;
while ( *pattern != '\0')
{
pattern++;
numberofcharacters++;
}
while ( *text != '\0' && pattern != '\0')
{
if ( *pattern == *text)
{
pattern++;
ct++;
text++;
}
else
{
text++;
}
}
if ( ct == numberofcharacters )
{
return(1);
}
else
{
return(0);
}
}
The idea is to compare the first character of the text variable with the pattern variable, lets take an example:
Suppose we have "TEXT" in text variable and "EX" in pattern:
I start to compare T with E, in this case, no match.
I point at E and compare again, there is a match.
Because of the match, I point at X in pattern and do the same in text, and I do another test.
2nd match,therefore, the number of characters in the pattern variable will be the same as the ct variable, which counts only when there is a match.
Therefore the return should be equal to 1.
The code returns always zero. I dont understand why ?

#include <stdio.h>
#include <stdlib.h>
int isIncluded(char *text, char* pattern);
int main()
{
char text[30];
char pattern[30]; int result;
printf(" Please introduce your text \n");
scanf("%s", text);
printf(" Please introduce the pattern you are looking for \n");
scanf("%s", pattern);
result = isIncluded( text, pattern);
if ( result == 1)
{
printf(" Your pattern has been found in your text \n " ) ;
}
if ( result == 0)
{
printf(" no substring found \n " ) ;
}
}
int isIncluded(char *text, char* pattern)
{
char *tempPattern = pattern;
int ct = 0;
int numberofcharacters = 0;
while ( *tempPattern != '\0')
{
tempPattern++;
numberofcharacters++;
}
while ( *text != '\0' && pattern != '\0')
{
if ( *pattern == *text)
{
pattern++;
ct++;
text++;
}
else
{
text++;
}
}
if ( ct == numberofcharacters )
{
return(1);
}
else
{
return(0);
}
}
It was the first loop that was problematic, because, as mentionned in the comment section, it completely changed the variable pattern to nothing, therefore there was nothing to compare to. This code works fine.

assuming this is a homework problem or you are learning consider this revision for starters:
int isIncluded ( char *text, char *pattern ); /* this is ok */
/*
can also write it this way
int isIncluded ( char text[], char pattern[] );
*/
int main ( void )
{
char text[30];
char pattern[30];
int result;
printf(" Please introduce your text \n");
scanf("%s", text); /* don't use &text here */
printf(" Please introduce the pattern you are looking for \n");
scanf("%s", pattern); /* don't use &pattern here */
/* don't pass a pointer to a pointer, the strings text and pattern are already pointers, you passing &text would mean isIncluded( char **text ) */
result = isIncluded( text, pattern );
if ( result == 1 )
{
printf(" Your pattern has been found in your text \n " ) ;
}
else if ( result == 0 )
{
printf(" no substring found \n " ) ;
}
else
{
/* don't overlook possibilities of missing simple stuff by not making use of else with if statements */
printf(" Error: value of result is %d\n", result );
}
}
I haven't looked into why isIncluded is always returning zero, but passing a pointer to a pointer to it was not helping.
If you are nice maybe I'll write partial code to get u started,
but what you are wanting to do is already completely accomplished by strstr() provided by # include <string.h>
also, defining char text[30] is the same a defining a pointer to type char called text but in addition it reserves space in memory to hold [n] characters which you said to be 30. It may be helpful in this case to understand the difference between defining and declaring in addition to what is actually happening when doing text[3] versus *(text+3) both of which are valid, unambiguous, and do the same thing.

In your isIncluded function first for calculating the length of pattern you change pattern and then was not the first one, you can calculate length with some other way like strlen but if you want to calculate with this way you should create a new variable as temp and change temp variable.
Another problem in this function in condition of end of pattern in second while loop should use *pattern != '\0' instead of pattern != '\0'
and when you want to call a function whit char* argument and you have array of character you should send array and &text type is char**
and in end here what you want:
#include <stdio.h>
#include <stdlib.h>
int isIncluded(char *text, char* pattern);
int main()
{
char text[30];
char pattern[30]; int result;
printf(" Please introduce your text \n");
scanf("%s", &text);
printf(" Please introduce the pattern you are looking for \n");
scanf("%s", &pattern);
result = isIncluded(text, pattern);
if (result == 1)
{
printf(" Your pattern has been found in your text \n ");
}
if (result == 0)
{
printf(" no substring found \n ");
}
}
int isIncluded(char *text, char* pattern)
{
int ct = 0;
int numberofcharacters = 0;
char *temp = pattern; //<- define new variable
while (*temp != '\0')
{
temp++;
numberofcharacters++;
}
while (*text != '\0' && *pattern != '\0')
{
if (*pattern == *text)
{
pattern++;
ct++;
text++;
}
else
{
text++;
}
}
if (ct == numberofcharacters)
{
return(1);
}
else
{
return(0);
}
}

Related

Function to reverse the input string.Display the reversed string but just with pointer no brackets[],no libraries..function will change in memory

int *i;
ters_cevir(){
char *term=i;
char *som=i;
char som1;
while (*term != '\0') { term++; }
while (*som != '\0') {
som1=som*;
*term=som;
term--;
som++;
}
}
int main() {
char *isim=malloc(sizeof(char));
i=&isim;
printf("Reverse words=");
scanf("%s",isim);
printf("Kelimenizin tersi:\n ");
ters_cevir(); // When I call this, it must make the reverse one that make from memory
while (*isim != '\0') {
printf("%c",*isim);
isim++;
sayac++;
}
return 0;
}
Hi I have modified your code. Please see below also see my comments:-
void ters_cevir(char *isim){
char *term=isim;
//char *som=isim;
//char som1;
while (*isim != '\0') { isim++; }
while (*term != '\0') {
//som1=som*;
*--isim=*term++//isim was pointing to the null character so we are pre decrement that pointer and post decrement term
//here we are coping the string in reverse order in isim
//term--;
//som++;
}
}
int main() {
char *isim=malloc(50);//you need enough space to store a string. you have just allocated only one byte which was not enough
//i=&isim;
printf("Reverse words=");
scanf("%s",isim);
printf("Kelimenizin tersi:\n ");
ters_cevir(isim); // now it will work fine. Here you are passing the address of isim
while (*isim != '\0') {
printf("%c",*isim);
isim++;
sayac++;
}
return 0;
}
Your code does not compile because of syntax errors such as som1=som*;
You should pass the string as an argument to ters_cevir(); instead of a global variable i with an incorrect type int *.
After fixing these problems, ters_cevir() will still not achieve the expected result because it overwrites the string from the end with characters from the start, with an off by one error.
You could correct this by swapping characters at *som and *term, but be careful to stop when som >= term otherwise you will reverse the string twice.
Futhermore, the code in main is completely broken.
Here is a corrected version:
#include <stdio.h>
char *reverse(char *str) {
char *term = str;
char *som = str;
char c;
while (*term != '\0') { term++; }
while (som < term) {
term--;
c = *som;
*som = *term;
*term = c;
som++;
}
return str;
}
int main() {
char buf[128];
printf("String to reverse: ");
if (scanf("%127[^\n]", buf) == 1) {
printf("Reversed string: %s\n", reverse(buf));
}
return 0;
}

Program to reverse a string in C without declaring a char[]

I need to reverse a given string and display it without using the value At[index] notation , I tried the below program using pointers,but it does not print anything for the reverse string,
Please help!
int main()
{
char* name=malloc(256);
printf("\nEnter string\n");
scanf("%s",name);
printf("\nYou entered%s",name);
int i,count;
count=0;
//find the length
while((*name)!='\0')
{
count++;
name++;
}
//pointer now at
printf("\n%p",name);
printf("\nLength is %d",count);
name=name+count;
//pointer now at
printf("\n%p",name);
for(i=0;i<(count);i++)
{
printf("%c",(*name));
name=name-1;
}
return 0;
}
Remove name=name+count; because of the name++ in the precedent loop moved name pointer to the '\0' char;
#include<stdio.h>
#include<stdlib.h>
int main()
{
char* name=malloc(256);
printf("\nEnter string\n");
scanf("%s",name);
printf("\nYou entered%s",name);
int i,count;
count=0;
//find the length and move name pointer
while((*name)!='\0')
{
count++;
name++;
}
//pointer now at
printf("\nPointer is: %p",name);
printf("\nLength is: %d\n",count);
for(i=1;i<=(count);i++)
{
printf("%c",*(name-i));
}
printf("\n");
return 0;
}
OR change the final loop to
for(i=0;i<(count);i++)
{
name--;
printf("%c",*name);
}
Remove name=name+count; and add name--;
Important: scanf(" %s", name); has no bounds checking on the input. If someone enters more than 255 characters into your program, it may give undefined behaviour.
Now, you have the char array you have the count (number of char in the array), and you make name++ (name has the last char offset) then why do you need to bother doing stuffs like this?
name=name+count;
Try this:
#include <stdio.h>
int main()
{
char* name = malloc(256);
// char name[256];
printf("\nEnter string\n");
// scanf("%s", name);
fgets(name, 254, stdin); // carriage return and null character (256-2)
printf("\nYou entered %s", name);
int i, count;
count = 0;
//find the length
while ((*name) != '\0' && (*name) != '\r') {
count++;
name++;
}
//pointer now at
// printf("\n%p", name);
// printf("\nLength is %d", count);
// name = name + count;
//pointer now at
// printf("\n%p", name);
for (i = count; i >= 0; i--) { // starts from last '\0'
printf("%c", (*name));
name = name - 1;
}
return 0;
}
I got the following output:
Enter string rakeb
You entered rakeb
bekar
The easiest way? Just replace them with their syntactic equivalent:
arr[index] // is sugar for ...
arr + index
Then, instead of using two indices to traverse just use pointers. Using this you can actually find a solution pretty easy:
void nreverse(char * str) {
char * forward = str;
char * backward = str + strlen(str) - 1;
while (forward < backward) {
char temp = *forward;
*forward = *backward;
*backward = temp;
++forward;
--backward;
}
}
Try this which will not only print but also reverse string and store it in name.
#include <stdio.h>
int main()
{
char* name = malloc(256);
char *backup1 = *bakcup2 = name;
printf("\nEnter string\n");
fgets(name, 254, stdin); // carriage return and null character (256-2)
printf("\nYou entered %s", name);
while ((*backup1) != '\0' && (*backup1) != '\r') {
backup1++;
}
backup1--; // Because here backup1 was pointing to '\0' or '\r'.
while(backup1 > backup2){
/* Swapping characters */
char temp;
temp = *backup1;
*backup1 = *backup2;
*backup2 = temp;
backup1--;
backup2++;
}
backup1 = name;
while(*backup1 != '\0' && *backup1 != '\r') {
printf("%c", (*backup1));
backup1++;
}
return 0;
}
Please post code that cleanly compiles
The current posted code is missing the required/used header files
the following code
1) includes error checking
2) limits the length of the user supplied string
to avoid a input buffer overflow
3) eliminates certain lines (commented out)
that caused 'name' to point to the wrong location
4) incorporates '\n' at the end of the printf() format strings
so the info will be printed rather than held
in the buffer for stdout
5) at the end, passes the pointer to the malloc'd memory
to the free() function
6) corrects the loop count when printing the
reverse of the input string
#include <stdio.h>
#include <stdlib.h>
#define MAX_NAME_LEN (256)
int main()
{
char* name=NULL;
char* temp = NULL;
if( NULL ==(name=malloc(256)) )
{ // then malloc failed
perror( "malloc for name[] failed");
exit( EXIT_FAILURE );
}
// implied else, malloc successful
temp = name; // save ptr to malloc'd memory
printf("\nEnter string\n");
if( 1 != scanf("%255s", name) )
{ // then scanf failed
perror( "scanf for name failed");
exit( EXIT_FAILURE );
}
// implied else, scanf successful
printf("\nYou entered: %s\n",name);
int i,count;
count=0;
//find the length
while((*name)!='\0')
{
count++;
name++;
}
//pointer now at
printf("\nAddress of last char in name[]: %p\n",name);
printf("\nLength is %d\n",count);
//name=name+count;
//pointer now at
//printf("\n%p",name);
for(i=0;i<=count;i++)
{
printf("%c",(*name));
name--;
}
printf( "\n" );
free(temp);
return 0;
} // end function: main

Restarting while loop in c without integers

I'm trying to get this code to work, but I have no idea how to restart the inner while loop. How would I do it?
/*
* Return a pointer to the first occurrence of any character in <stop>
* in the given <string> or NULL if the <string> contains no characters
* in <stop>.
*****
* YOU MAY *NOT* USE INTEGERS OR ARRAY INDEXING.
*****
*/
char *find_any_ptr(char *string, char* stop) {
char *newstring = (char*)0;
while(*stop != '\0'){
while(*string != '\0') {
if(*string == *stop){
if(newstring < string || newstring != (char*)0){
string++;
}else{
newstring = string;
string++;
}
}
}
stop++;
}
return newstring; // placeholder
}
Use a temporary variable for string pointer, and use this temp variable instead inside the inner loop.
while(*stop != '\0'){
char *p = string;
while (*p != '\0') {
... /* use 'p' in place of 'string' */
}
stop++;
}
This is relatively simple using nothing but a character pointer to the string and a pointer to stop. For each character in your string, you compare against each character in stop, returning the character in string on match, or NULL if no match is found:
#include <stdio.h>
char *find_any_index(char string[], char stop[]) {
char *p = string;
char *sp = NULL;
while (*p)
{
sp = stop;
while (*sp)
{
if (*sp == *p)
return p;
sp++;
}
p++;
}
return NULL;
}
int main (int argc, char **argv) {
if (argc < 3) {
printf ("usage: %s string stoplist\n", argv[0]);
}
printf ("\n string: %s\n stop : %s\n\n", argv[1], argv[2]);
printf (" first char in string matching a char in stop: %s\n\n", find_any_index (argv[1], argv[2]));
return 0;
}
Output
$ ./bin/find_substr_str thisIsAstring mase
string: thisIsAstring
stop : mase
first char in string matching a char in stop: sIsAstring
Here is a demonstrative program that shows how the function can be written
#include <stdio.h>
char * find_any_ptr( const char *string, const char* stop )
{
const char *p, *q;
_Bool found = 0;
p = string;
do
{
q = stop;
while ( *q && *q != *p ) ++q;
} while ( !( found = *q ) && *++p );
return ( char * )( found ? p : NULL );
}
int main(void)
{
const char *p = find_any_ptr( "abc9de", "1234567890" );
if ( p ) puts( p );
return 0;
}
The program output is
9de
Only I would name the function find_any_char instead of find_any_ptr:)
This is my implementation:
#include <stdio.h>
#include <stdlib.h>
char * findany(char *string, char *stop) {
char * app;
//To avoid segmentation fault!
if (stop==NULL || string==NULL || !*stop || !*string)
return NULL;
do {
app=string;
while(*app!=0 && *app!=*stop)
app++;
stop++;
} while(*app==0 && *stop!=0);
return (*app!=0)?app:NULL;
}
int main(void)
{
char string[100];
char stop[100];
char * found;
for(;;) {
printf("Insert a string without spaces[q<Enter> to exit]: ");
scanf("%s",string);
if (!strcmp(string,"q"))
break;
printf("Insert the chars to search without spaces: ");
scanf("%s",stop);
printf("Searching any occurence of a char in \"%s\""
" inside \"%s\"\n",stop,string);
found=findany(string,stop);
printf("%s\n",(found!=NULL)?found:"NULL");
}
return 0;
}
I think that is better to use also the following way to implement the function findany():
char * _findany(char *string, char *stop) {
char * app; // to start the first loop
//To avoid segmentation fault!
if (stop==NULL || string==NULL || !*stop || !*string)
return NULL;
do {
app=stop;
while(*app!=0 && *app!=*string)
app++;
string++;
} while(*app==0 && *string!=0);
return (*app!=0)?(string-1):NULL;
}
You may observe the difference between the two functions adding the function _findany in the code above and to call the new function adding the following code after (or before) the printf in the main above.
found=_findany(string,stop);
printf("%s\n",(found!=NULL)?found:"NULL");

how to check for numbers in a certain position in a string and extracting its value in c?

I'm supposed to write a function not using other libraries but that gets a string from a user (up to 100 chars). the string would be in this form: a,b,c,d,x,y,z etc... from which i'm supposed to extract only the first whole numbers in between commas to a different array.
so for example let's say i get this as an input: abcd,32,23.5,4,6,hf3,45g,2
the numbers in the new array should be: 32,4,6,2 because these are the first 4 numbers you can see in the input. if there was no number found the default value will be 0.
this is what i've been doing so far, but somehow it doesn't seem to be right,
the idea was to check each char seperately, and unless a comma was seen and the char is between the ASCII value of '0' and '9' to sum them. if a different char was seen before the comma, then "skip" will get the value 1, this way the function will keep looking for another number.
thanks for the help.
int getParameters()
{
char input[100];
int parameters[4]={0};
int indexInput=0, indexParameters;
int charValue=0;
int skip=1;
scanf("%s", input);
for (indexParameters=0; indexParameters<4;skip=0)
{
if (input[indexInput]=='\0')
break;
else
{
for (;input[indexInput]!=','; ++indexInput)
{
printf("%c\n", input[indexInput]);
if(input[indexInput]=='\0')
break;
else if (input[indexInput]<'9' &&
input[indexInput]>'0')
{
charValue=input[indexInput]-'0';
parameters[indexParameters]*=10;
parameters[indexParameters]+=charValue;
}
else
{
skip=1;
}
}
}
indexInput++;
if (input[indexInput]==",")
skip==1;
if (skip==1)
{
parameters[indexParameters]=0;
}
else
indexParameters++;
}
return 0;
}
sample by strtok and strtol
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(){
char input[100] = "abcd,32,23.5,4,6,hf3,45g,2";
char *token = strtok(input, ",");
while(token){
char *endp;
int num = strtol(token, &endp, 10);
if(*endp == '\0')
printf("%d\n", num);
//else //not integer.
token = strtok(NULL, ",");
}
return 0;
}
without strtok
#include <stdio.h>
#include <stdlib.h>
int main(){
char input[100] = "abcd,32,23.5,4,6,hf3,45g,2";
char *p = input;
while(*p){
char *endp;
int num = strtol(p, &endp, 10);
if(*endp == ',' || *endp == '\0')
printf("%d\n", num);
//else //not integer.
//skip to next read point
p = endp;
while(*p != ',' && *p)
++p;
if(*p)
++p;
}
return 0;
}
solved the problem, tried a different algorithm just with one loop:
int getParameters()
{
char input[100];
int parameters[4]={0};
int indexInput=0, indexParameters=0;
int skip=0, numberSeen=0;
scanf("%s", input);
for (;input[indexInput]!='\0' && indexParameters<4;++indexInput)
{
if (input[indexInput]==',' && skip==1)
{
parameters[indexParameters]=0;
skip=0;
}
else if (input[indexInput]==','&& numberSeen==1)
{
numberSeen=0;
indexParameters++;
}
else if (input[indexInput]==',')
continue;
else if (input[indexInput]<='9' && input[indexInput]>='0')
{
parameters[indexParameters]*=10;
parameters[indexParameters]+=input[indexInput]-'0';
numberSeen=1;
}
else
skip=1;
}
return 0;
}

Wierd Problems With My Own Custom Written Word Search Algorithm

My sister and I recently got an assignment in C to write a function which finds a specific word in a string, and if found, returns the first letter index of that word found in the string. But all sorts of problems popped up...
Main File [testing_word_search.c]
#include <stdio.h>
#include "u_s_search_word_in_string.h"
int main()
{
int first_letter_idx = 0;
char line[32] = "Janen is a dog";
char word[4] = "dog";
first_letter_idx = search_word_in_string( line, word );
printf("\nThe beginning of the word is at index %d.\n", first_letter_idx );
return 0;
};
Functions [u_s_search_word_in_string.c]
#include <stdio.h>
#include "u_s_search_word_in_string.h"
int search_word_in_string ( char line[], /* ( Input ) */
char word[] /* ( Input ) Word to search for in {line}. )
{
int line_idx = 1;
int word_idx = 1;
int first_letter_idx = 0;
/* Finding word. */
while ( (line[line_idx] != '\0') )
{
if ( (line[line_idx] = word[word_idx]) && (word[word_idx] != '\0') )
{
/* Index of beginning letter of word set to another variable. */
if ( (first_letter_idx = 0) )
{
first_letter_idx = line_idx;
}
line_idx++;
word_idx++;
}
else
{
/* If word turns out to be not found, continue. */
first_letter_idx = 0;
line_idx++;
word_idx++;
};
};
if ( (first_letter_idx = 0) )
{
puts("Cannot find word in string.");
return -1;
};
if ( first_letter_idx >= 1 )
{
puts("Found word, returning first letter index.");
};
return (first_letter_idx);
};
Function's header file. [u_s_search_word_in_string.h]
int search_word_in_string ( char line[], /* ( Input ) */
char word[] /* ( Input ) Word to search for in {line}. */ );
Sorry if the comments may seem crappy, I will work on them later, but I don't know what is wrong...
First of all, when compiling there isn't a warning about using Puts(), second, the compile tells me everything was successful but when I execute it, this happens:
./geany_run_script.sh: 5: ./geany_run_script.sh: ./testing_word_search: not found
My inputed build command:
Compile: gcc -Wall -c testing_word_search.c
u_s_search_word_in_string.c Build: gcc -o word_search
testing_word_search.o u_s_search_word_in_string.o Execute: "./%e"
Usual default setting, I know that if I want to run a program I must go to the main module.
And when I run it using the terminal, it says this:
The beginning of the word is at index 0.
There should be another message other then this technically.
I would really be thankful if one of you members points out my mistake, because so far, I am clueless as to what I might be doing wrong.
Some issues with your code:
You don't need semicolons after a block of statements (i.e. after the closing bracket }).
You have to compare your chars via == and not via = (first is a comparison, second is an assignment).
line_idx and word_idx should be zero (because the string you are looking for can also exist at the beginning).
first_letter_idx should default to -1 (because, again, 0 is a valid value), and you should check for -1 and not for 0 to know if the search failed.
The rest seems okay, but you can shorten your code a bit (e.g. the check word[word_idx] != '\0' is unnecessary; also line_idx++; and word_idx++; can be written beneath the if-else statement, because they get executed no matter what happens.)
I hope this solves most of your problems.
The header string.h provides a function strstr that is tailor made for what you are trying to accomplish. Full example:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char *string = NULL;
char *substr = NULL;
char *p = NULL;
printf ("\nEnter string : ");
scanf ("%m[^\n]%*c", &string);
printf ("\nEnter substr : ");
scanf ("%m[^\n]%*c", &substr);
if ((p = strstr (string, substr)) != NULL)
printf ("\nSubstring found beginning at : %c (char '%lu' in string)\n\n",
*p, p - string + 1);
else
printf ("\nSubstring NOT in string.\n\n");
if (string) free (string);
if (substr) free (substr);
return 0;
}
output:
$ ./bin/strstrc
Enter string : Janen is a dog
Enter substr : dog
Substring found beginning at : d (char '12' in string)
If you must do it without using strstr, then the link in the comment will help.
Check the below code:
#include <stdio.h>
#include<string.h>
int search_word_in_string ( char line[], /* ( Input ) */
char word[] )
{
int line_idx = 0;
int k;
int word_idx = 0;
int first_letter_idx = 0;
/* Finding word. */
while ( (line[line_idx] != '\0') )
{
word_idx =0;
if(line[line_idx] == word[word_idx])
{
k = line_idx;
while(word[word_idx] != '\0' && word[word_idx] == line[k])
{
k++;
word_idx++;
}
if((k-line_idx) == strlen(word))
return line_idx+1;
}
line_idx++;
}
return -1;
}
int main()
{
int first_letter_idx = 0;
char line[32] = "Janen is a dog";
char word[4] = "is";
first_letter_idx = search_word_in_string( line, word );
if(first_letter_idx > -1)
printf("\nThe beginning of the word is at index %d.\n", first_letter_idx );
else
printf("\n String not found \n");
return 0;
}
Well thank you Philipp and Bluepixy, I updated my code:
/*
* Author: Usia, Sebastian
* Date: 21/NOV/2014
*
* Input: Two character type variables.
* Output: Index number of beginning letter of word.
*
* Description: Uses an algorithm to find a word in a string and if found
* it returns the index number of the first letter of the found word.
*
*/
#include <stdio.h>
#include "u_s_search_word_in_string.h"
int search_word_in_string ( char line[], /* ( Input ) */
char word[] /* ( Input ) Word to search for in {line}. */ )
{
int line_idx = 0;
int word_idx = 0;
int first_letter_idx = 0;
int word_length = 0;
int matched = 0; /* Number of consecutive characters matching between {word} and {line}. */
/* Find {word}'s length. */
while (word [word_length] != '\0') word_length++;
printf("word length is %d\n", word_length);
/* Finding word. */
while ( (line[line_idx] != '\0') && (matched != word_length) )
{
printf("before IF: line_idx = %d, word_idx = %d\n", line_idx, word_idx);
if ( (word[word_idx] != '\0') && (line[line_idx] == word[word_idx]) )
{
printf("*match* line_idx = %d, word_idx = %d\n", line_idx, word_idx);
/* Marking {word}'s first letter in the text line. */
if ( (word_idx == 0) )
{
first_letter_idx = line_idx;
}
matched++;
word_idx++;
}
else
{
printf("letters do not match --- line_idx = %d, word_idx = %d\n",line_idx, word_idx);
/* If letters don't match, reset word_idx and match counter. */
word_idx = 0;
matched = 0;
};
line_idx++; /* No matter what we move ahead the {line_idx}. */
};
printf("matched %d\n", matched );
if ( matched == word_length )
{
printf("Found word, returning first letter index.");
return (first_letter_idx);
}
else
{
printf("Cannot find word in string.");
return -1;
};
};
Added traces just to be sure.
I never really heard of "strstr" before, I will check it out sometime soon. Thanks again.

Resources