Wednesday, April 30, 2025

C Program - strncpy() Function - Copy Specific Number of Characters from a String to Another String

This is a C program that demonstrates how to copy a specific number of characters from one string to another using the strncpy() function. 

//copy just specific number of charactes from string

#include <stdio.h>
#include <string.h>

int main()
{

    char some_string[] = "Hack The Planet, coz it's fun.";

    char target_string[20]; //ako stavis vise onda je garbage

    printf("Some String: %s \n", some_string);
    printf("Initial Target String: %s \n", target_string);

    strncpy(target_string, some_string, 10); //150, 5

    printf("Final Target String: %s \n", target_string);

    return 0;

}

Result: 

Some String: Hack The Planet, coz it's fun.
Initial Target String:
Final Target String: Hack The P

Process returned 0 (0x0)   execution time : 0.031 s
Press any key to continue.

Here's a breakdown of the code block by block: 

#include <stdio.h>
#include <string.h>

These are header files that are included in the program to provide definitions for functions used later in the code. stdio.h is included for standard input/output functions, while string.h is included for string manipulation functions. 

int main()
{

This is the main function of the program, where execution begins. The function returns an integer value (in this case, 0) to indicate the status of the program when it exits. 

    char some_string[] = "Hack The Planet, coz it's fun.";

    char target_string[20];

    printf("Some String: %s \n", some_string);
    printf("Initial Target String: %s \n", target_string);

This declares two character arrays: some_string and target_string. The former is initialized with a string literal, while the latter is left uninitialized.

The program then uses printf() to display the original input string some_string and an initial value of target_string on the console. 

    strncpy(target_string, some_string, 10);

    printf("Final Target String: %s \n", target_string);

The strncpy() function is used to copy the first 10 characters of some_string into target_string. The strncpy() function is similar to strcpy(), but it takes an additional argument that specifies the maximum number of characters to copy.

If the source string is shorter than the specified length, the remaining characters in the destination string are padded with null characters.

Finally, the program uses printf() to display the final value of target_string

    return 0;
}

This statement ends the main() function and returns the value 0 to indicate successful program execution.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...