Sunday 22 January 2017

Finding the last occurrence of a word in a given string using a C program(c programming examples)(c program examples)

Finding the last occurrence of a word in a given string using a C program

This program is an example for the beginners to practice and improve their skill.  This program is written on the base of basic C programming, for loop and some conditions. There are fewer tools, but we can do anything with those tools in C programming.


If you want to see this code with a perfect indentation, copy the code into "sublime text editor" and make sure that the type of code is set to 'c' at the bottom right of the window. After pasting the code press the command "ctrl+shift+P", you get a search box. Type "indentation" you get an option like this below the search box "Indentation: Reindent lines". Clink on that to get the code with indentation. 



The program is as follows:

#include <stdio.h>

#include <string.h>
main()
{
char string[1000],word[100];
int i,j=0,index=1,len,len1,posi=0;
printf("enter the string\n");
gets(string);
len1=strlen(string);
printf("enter the word to identify its last position\n");
gets(word);
len=strlen(word);
j=len-1;
for(i=0;string[i]!='\0';i++)
{
if(string[i]!='\n' && string[i]!=' ' && string[i]!='\t')
if(string[i+1]=='\n'||string[i+1]==' '||string[i+1]=='\t')
index++;
}
for(i=len1;i>=0;i--)
{
if(string[i]!='\n' && string[i]!=' ' && string[i]!='\t')
if(string[i-1]=='\n'||string[i-1]==' '||string[i-1]=='\t')
index--;
if(word[j]==string[i])
{
if(j>0)
j--;
if(j==0 && len==1)
posi=index+1;
if(j==0 && len!=1)
{
posi=index;
break;
}

}
}
if(posi==0)
printf("the word you enetered is not in the string\n");
else
printf("the word you entered contains the word index %d in the string\n",posi );
return 0;
}


The output is as follows::




char string[1000],word[100];

Before writing the code an algorithm is an important step to solving the problem quickly.  The problem is to find the last occurrence of a word in a string.  In C the data type 'char' is used to store the given character.  But storing of a single character won't help in solving our problem.  So, we use arrays to store the entire string.  Storing is done, but a lot of puzzling operations are ahead.  We have to find a word in the string so, another array should be there to store the word. Declare two arrays.

int i,j=0,index=1,len,len1,posi=0;

In integers, we can simply find whether they are equal or not by the condition '==' or '!='. But in arrays, every single character in the array should be checked with the character of another string. So, to this happen, we use for loop to check the elements in the two arrays. The address of the array starts from '0'.  After all the characters stored in individual boxes of an array, the end box after storing the last character of the string is filled with a null character representing that it is the end. So, to browse all the boxes of the array we should declare integers to address the character in the array. The integers 'len' and 'len1' are declared to store the lengths of both the strings given by the user. The integer 'index' is declared to get the number of words and position of words in the string. The integer 'posi' is declared to print the position of the word in the string.

 printf("enter the string\n");
gets(string);
len1=strlen(string);
printf("enter the word to identify its last    position\n");
gets(word);
len=strlen(word);


The above lines are very basics. Printf function is used to print whatever we want to print on the screen. We can print messages or we can print integers, character using '%d' and '%c' and '%s' etc...
The gets function is used to store to input given by the user into anything that is written in between the brackets.  The two functions we have discussed up to now are written in 'stdio.h'. To execute these function we should include 'stdio.h' header file so that the execution process calls the function in the library to perform the required action on it.  'strlen()' is the function included in 'string.h' header file to find out the length of the string.



j=len-1;

The address of an array starts with zero. Length is calculated from one. So, the integer 'j' is assigned by decreasing the value of 'len' by one.

for(i=0;string[i]!='\0';i++)
{
if(string[i]!='\n' && string[i]!=' ' && string[i]!='\t')
if(string[i+1]=='\n'||string[i+1]==' '||string[i+1]=='\t')
index++;
}

By using this loop we calculate the number of words in the string and their indexes. A word is considered as a group of character without any space or tabs or newline characters in between the letters. So, we use this loop to check the end of the word.  After the last character of the word, there should be a space or tab or newline. Whenever both the conditions satisfied the value of the index is increased by one. At the end, the loop terminates and the value of index represents the number of words in the string.

for(i=len1;i>=0;i--)
{
if(string[i]!='\n' && string[i]!=' ' && string[i]!='\t')
if(string[i-1]=='\n'||string[i-1]==' '||string[i-1]=='\t')
index--;
if(word[j]==string[i])
{
if(j>0)
j--;
if(j==0 && len==1)
posi=index+1;
if(j==0 && len!=1)
{
posi=index;
break;
}

}
}

The logic used in the loop is to find the first occurrence of the word from the last. So, it will be the last occurrence of the word. The 'break;' command is used to terminate the loop when we find the occurrence of the word. In the first three lines of the body in the loop is used to find the position of the word where it is found. If the last character of the word is matched with any address of the array, the value of 'j' is decreased by one to check the preceding character with the preceding box of the array which contains the string.  I the value of 'j' becomes zero, it states that all the characters of the word are found in the string and value of 'index' is assigned to 'posi'.

if(posi==0)
printf("the word you enetered is not in the string\n");
else
printf("the word you entered contains the word index %d in the string\n",posi );

The value of 'posi' is tested in these conditions whether the word is found in the string or not.  If the word is found the value of 'posi' never be zero.  So, among these two conditions, one will be satisfied.


C is a general-purpose programming language. It has been closely associated with the UNIX system where is was developed, since both the system and most of the programs that run on it are written in C. The language, however, is not tied to any one operating system or machine; and although it has been called a “system programming language” because it is useful for writing compilers and operating systems, it has been used equally well to write major programs in many different domains.(c programming examples)(c program examples)
Many of the important ideas of C stem from the language BCPL, developed by Martin Richards. The influence of BCPL on C proceeded indirectly through the language B, which was written by Ken Thompson in 1970 for the first UNIX system on the DEC PDP-7.(c programming examples)
BCPL and B are “typeless” languages. By contrast, C provides a variety of data types. The fundamental types are characters, and integers and floating point numbers of several sizes. In addition, there is a hierarchy of derived data types created with pointers, arrays, structures, and unions. Expressions are formed from operators and operands; any expression, including an assignment or a function call, can be a statement. Pointers provide for machine-independent address arithmetic.(c programming examples)(c program examples)
C provides the fundamental control-flow constructions required for well-structured programs: statement grouping, decision making (if-else), selecting one of a set of possible cases (switch), looping with the termination test at the top (while, for) or at the bottom (do), and early loop exit (break).(c programming examples)(c program examples)
Functions may return values of basic types, structures, unions, or pointers. Any function may be called recursively. Local variables are typically “automatic,” or created anew with each invocation. Function definitions may not be nested but variables may be declared in a block-structured fashion. The functions of a C program may exist I separate source files that are compiled separately. Variables may be internal to a function, external but know only within a single source file, or visible to the entire program.(c programming examples)(c program examples)
A preprocessing step performs macro substitution on program text, inclusion of other source files, conditional compilation.(c programming examples)(c program examples)
C  is a relatively “low level” language. This characterization is not pejorative; it simply means that C deals with the same sort of object that most computers do, namely characters, numbers, and addresses. These may be combined and moved about with the arithmetic and logical operators implemented by real machines.(c programming examples)(c program examples)
C provides no operations to deal directly with composite objects such as character strings, sets, lists, or arrays. There are no operations that manipulate an entire array or string, although structures may be copied as a unit. The language does not define any storage allocation facility other than static definition and the stack discipline provided by the local variables of functions; there is n heap or garbage collection. Finally, C itself provides no input/output facilities; there are no READ or WRITE statements, and no built-in file access methods. All of these higher-level mechanisms must be provided by explicitly called functions. Most C implementations have included a reasonably standard collection of such functions.(c programming examples)(c program examples)


1 comment :