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.

  1. Declare and Initialize Variables:
  2. char str[] = "Hello, World!"; initializes a character array with the string "Hello, World!".
  3. int start = 7; defines the starting index of the substring.
  4. int length = 5; specifies the length of the substring.

  5. Create Substring:

  6. char substr[length + 1]; declares a character array to store the substring.
  7. strncpy(substr, &str[start], length); uses the strncpy function to copy a specified number of characters from the original string to the substring.
  8. substr[length] = '\0'; adds a null terminator at the end of the substring to ensure it is properly terminated.

  9. Print Substring:

  10. printf("The substring is: %s\n", substr); prints the resulting substring.

This code will output the substring "World" from the original string "Hello, World!".