C Programming Code Examples
C > Strings Code Examples
program to replace first occurrence of a character in a string
/* program to replace first occurrence of a character in a string
Write a C program to replace first occurrence of a character with another character in a string. How to replace first occurrence of a character with another character in a string using loop in C programming. Logic to replace first occurrence of a character in given string.
Logic to replace first occurrence of a character
Input string from user, store it in some variable say str.
Input character to replace and character new character from user, store it in some variable say oldChar and newChar.
Run a loop from start of string str to end. The loop structure should loop like while(str[j]!='\0')
Inside the loop check if(str[j] == oldChar). Then, swap old character with new character i.e. str[j] = newChar and terminate the loop.
C program to replace first occurrence of a character with another in a string */
#include <stdio.h>
#define maxsize 100 // Maximum string size
/* Function declaration */
void replaceFirst(char * str, char oldChar, char newChar);
int main()
{
char str[maxsize], oldChar, newChar;
printf("Enter any string: ");
gets(str);
printf("Enter character to replace: ");
oldChar = getchar();
// Used to skip extra ENTER character
getchar();
printf("Enter character to replace '%c' with: ", oldChar);
newChar = getchar();
printf("\nString before replacing: %s\n", str);
replaceFirst(str, oldChar, newChar);
printf("String after replacing first '%c' with '%c' : %s", oldChar, newChar, str);
return 0;
}
/* Replace first occurrence of a character with another in given string. */
void replaceFirst(char * str, char oldChar, char newChar)
{
int j=0;
/* Run till end of string */
while(str[j] != '\0')
{
/* If an occurrence of character is found */
if(str[j] == oldChar)
{
str[j] = newChar;
break;
}
j++;
}
}
While loop is also known as a pre-tested loop. In general, a while loop allows a part of the code to be executed multiple times depending upon a given boolean condition. It can be viewed as a repeating if statement. The while loop is mostly used in the case where the number of iterations is not known in advance. The while loop evaluates the test expression inside the parentheses (). If test expression is true, statements inside the body of while loop are executed. Then, test expression is evaluated again. The process goes on until test expression is evaluated to false. If test expression is false, the loop terminates.
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).
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 character from stdin. Returns the next character from the standard input (stdin). It is equivalent to calling getc with stdin as argument. A getchar() function is a non-standard function whose meaning is already defined in the stdin.h header file to accept a single input from the user. In other words, it is the C library function that gets a single character (unsigned char) from the stdin. However, the getchar() function is similar to the getc() function, but there is a small difference between the getchar() and getc() function of the C programming language.
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.
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.
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 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:
C program to remove all Repeated characters in a String using loops. Input string from user. Remove all duplicate characters from a given string. Remove all occurrences of a character
'Quicksort' is a divide and Conquer algorithm. 'Pick an element' from the array, this element is called as pivot element, divide the unsorted 'array of elements' in 2 arrays with values less
C program to input elements in an array from user and sort all even and odd elements of the given array separately without using any other array. If minimum element of the array
C program code input two numbers from user and calculate their sum. C program to add 2 numbers and printing their sum as output. How to add two numbers in C programming.