print a part of string c
Code to Print a Part of a String in C
You can use the following code to print a part of a string in C:
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello, World!";
int start = 7;
int length = 5;
char substr[length + 1];
strncpy(substr, &str[start], length);
substr[length] = '\0';
printf("The substring is: %s\n", substr);
return 0;
}
Explanation:
1. Include Necessary Libraries:
- The #include <stdio.h>
and #include <string.h>
lines are used to include the necessary libraries for input/output and string manipulation functions, respectively.
- Declare and Initialize Variables:
char str[] = "Hello, World!";
initializes a character array with the string "Hello, World!".int start = 7;
defines the starting index of the substring.int length = 5;
specifies the length of the substring.Create Substring:
char substr[length + 1];
declares a character array to store the substring.strncpy(substr, &str[start], length);
uses thestrncpy
function to copy a specified number of characters from the original string to the substring.substr[length] = '\0';
adds a null terminator at the end of the substring to ensure it is properly terminated.Print Substring:
printf("The substring is: %s\n", substr);
prints the resulting substring.
This code will output the substring "World" from the original string "Hello, World!".