Home »
Programming Tips & Tricks »
C - Tips & Tricks
Terminate any string from given index in C language
By: IncludeHelp, on 03 MAR 2017
Learn: How to terminate any string from a given index using NULL character.
This is a simple C language trick, by using this you can terminate any string from given index by assigning NULL.
We are aware that string is terminated with NULL, if we are reading a string from the keyboard, the associated function like (scanf, fgets, gets...) inserts a NULL character at the end of the string, like these functions we can also insert NULL at any index to terminate the string.
Let suppose there is a string "Hello world" and you want to keep only "Hello" in the original string (character array) variable. You can assign NULL at the index 5 (counting from 0) and string will be terminated.
Consider this example
#include <stdio.h>
int main()
{
char str[]="Hello world";
printf("str before terminating: %s\n",str);
//assign NULL at index 5
str[5]='\0';
printf("str after terminating: %s\n",str);
return 0;
}
Output
str before terminating: Hello world
str after terminating: Hello
Using user define function
#include <stdio.h>
//declaration
void terminate(char *str,int index);
int main()
{
char str[]="Hello world";
printf("str before terminating: %s\n",str);
//function calling
terminate(str,5);
printf("str after terminating: %s\n",str);
return 0;
}
//definition
void terminate(char *str,int index){
str[index]='\0';
}