C Programming Code Examples
C > Strings Code Examples
C program to remove last occurrence of a word in string
/* C program to remove last occurrence of a word in string
Write a C program to remove from last occurrence of a word in given string using loop. How to remove the last occurrence of any word in given string using loop in C programming. Logic to remove last occurrence of a word from given string.
Logic to remove last occurrence of a word
Input string from user, store it in some variable say str.
Input word to be searched from user, store it in some other variable say word.
Initialize a variable to store last matched index of word in given string, say index = -1. I have initially assumed that given word does not exists in string hence initialized with -1.
Run a loop from start of the string str to end.
Inside loop, for each character in word match the rest of characters with str. If all characters in word and str matches then, update index with current match position.
Finally, after loop if index != -1 then, word has been found. Hence, shift all characters to left from the current index position. */
#include <stdio.h>
#include <string.h>
#define maxsize 100 // Maximum string size
int main()
{
char str[maxsize];
char word[maxsize];
int x, j, found, index;
int stringLen, wordLen;
/* Input string and word from user */
printf("Enter any string: ");
gets(str);
printf("Enter word to remove: ");
gets(word);
stringLen = strlen(str); // Length of string
wordLen = strlen(word); // Length of word
/* Run loop from start to end of string - word length */
index = -1;
for(x=0; x<stringLen - wordLen; x++)
{
// Match word at current position
found = 1;
for(j=0; j<wordLen; j++)
{
// If word is not matched
if(str[x+j] != word[j])
{
found = 0;
break;
}
}
// If word is found then update index
if(found == 1)
{
index = x;
}
}
// If word not found
if(index == -1)
{
printf("'%s' not found.");
}
else
{
/* Shift all characters from right to left */
for(x=index; x <= stringLen - wordLen; x++)
{
str[x] = str[x + wordLen];
}
printf("String after removing last '%s': \n%s", word, str);
}
return 0;
}
The for loop is used in the case where we need to execute some part of the code until the given condition is satisfied. The for loop is also called as a per-tested loop. It is better to use for loop if the number of iteration is known in advance. The for-loop statement is a very specialized while loop, which increases the readability of a program. It is frequently used to traverse the data structures like the array and linked list.
Writes the C string pointed by format to the standard output (stdout). If format includes format specifiers (subsequences beginning with %), the additional arguments following format are formatted and inserted in the resulting string replacing their respective specifiers. printf format string refers to a control parameter used by a class of functions in the input/output libraries of C programming language. The string is written in a simple template language: characters are usually copied literally into the function's output, but format specifiers, which start with a % character, indicate the location and method to translate a piece of data (such as a number) to characters. "printf" is the name of one of the main C output functions, and stands for "print formatted". printf format strings are complementary to scanf format strings, which provide formatted input (parsing). In both cases these provide simple functionality and fixed format compared to more sophisticated and flexible template engines or parsers,
Get string from stdin. Reads characters from the standard input (stdin) and stores them as a C string into str until a newline character or the end-of-file is reached. The newline character, if found, is not copied into str. A terminating null character is automatically appended after the characters copied to str. Notice that gets is quite different from fgets: not only gets uses stdin as source, but it does not include the ending newline character in the resulting string and does not allow to specify a maximum size for str (which can lead to buffer overflows).
C supports nesting of loops in C. Nesting of loops is the feature in C that allows the looping of statements inside another loop. Any number of loops can be defined inside another loop, i.e., there is no restriction for defining any number of loops. The nesting level can be defined at n times. You can define any type of loop inside another loop; for example, you can define 'while' loop inside a 'for' loop.
The if-else statement is used to perform two operations for a single condition. The if-else statement is an extension to the if statement using which, we can perform two different operations, i.e., one is for the correctness of that condition, and the other is for the incorrectness of the condition. Here, we must notice that if and else block cannot be executed simiulteneously. Using if-else statement is always preferable since it always invokes an otherwise case with every if condition.
#include is a way of including a standard or user-defined file in the program and is mostly written at the beginning of any C/C++ program. This directive is read by the preprocessor and orders it to insert the content of a user-defined or system header file into the following program. These files are mainly imported from an outside source into the current program. The process of importing such files that might be system-defined or user-defined is known as File Inclusion. This type of preprocessor directive tells the compiler to include a file in the source code program. Here are the two types of file that can be included using #include:
In the C Programming Language, the #define directive allows the definition of macros within your source code. These macro definitions allow constant values to be declared for use throughout your code. Macro definitions are not variables and cannot be changed by your program code like variables. You generally use this syntax when creating constants that represent numbers, strings or expressions.
In C, the "main" function is treated the same as every function, it has a return type (and in some cases accepts inputs via parameters). The only difference is that the main function is "called" by the operating system when the user runs the program. Thus the main function is always the first code executed when a program starts. main() function is a user defined, body of the function is defined by the programmer or we can say main() is programmer/user implemented function, whose prototype is predefined in the compiler. Hence we can say that main() in c programming is user defined as well as predefined because it's prototype is predefined. main() is a system (compiler) declared function whose defined by the user, which is invoked automatically by the operating system when program is being executed.
The break is a keyword in C which is used to bring the program control out of the loop. The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.
Get string length. Returns the length of the C string str. The length of a C string is determined by the terminating null-character: A C string is as long as the number of characters between the beginning of the string and the terminating null character (without including the terminating null character itself).
Input a 'string from user', store it in a variable say str. 'Declare another Array' that will store 'reverse of the string', say char reverse[SIZE]. Find Length of the string and store it in some
C Program prints all the elements of Nth level in single line. Structure of binary tree node. Add node to binary tree. Height of the binary tree. Finds the nearest common ancestor. If
Step by step descriptive logic to create menu driven calculator that performs all basic math operations. Input 2 numbers and a Character from user in the given format. Store them in
C program, using recursion, 'Performs Merge' sort. A Merge Sort is a sorting algorithm with 'Complexity of O(nlogn)'. It is used for sorting numbers, structure, files. Perform Merge Sort
Lets take 2 Strings as input and store them in the arrays string1[] and string2[] respectively. "Count the Number" of characters in both the arrays and store the result in the variables co1
C First give a meaningful name to our prime checking function say isPrime() function will check a number for prime. Since our function checks a number for prime condition. Hence
You can 'concatenate two strings' easily using standard library function strcat() but, in this C program 'concatenates two strings' manually without using 'strcat()' function. Calculate the