Wednesday, October 9, 2024
Google search engine
HomeData Modelling & AIHow to Append a Character to a String in C

How to Append a Character to a String in C

Given a string str and a character ch, this article tells about how to append this character ch to this string str at the end.
Examples: 
 

Input: str = "Geek", ch = 's'
Output: "Geeks"

Input: str = "skee", ch = 'G'
Output: "skeeG"

Approach
 

  1. Get the string str and character ch
  2. Use the strncat() function to append the character ch at the end of str. strncat() is a predefined function used for string handling. string.h is the header file required for string functions.
    Syntax: 
     
char *strncat(char *dest, const char *src, size_t n)

Parameters: This method accepts the following parameters: 
 

  • dest: the string where we want to append.
  • src: the string from which ‘n’ characters are going to append.
  • n: represents the maximum number of character to be appended. size_t is an unsigned integral type.

       3. Print or return the appended string str.

Below is the implementation of the above approach:
 

C




// C program to Append a Character to a String
 
#include <stdio.h>
#include <string.h>
 
int main()
{
    // declare and initialize string
    char str[6] = "Geek";
 
    // declare and initialize char
    char ch = 's';
 
    // print string
    printf("Original String: %s\n", str);
    printf("Character to be appended: %c\n", ch);
 
    // append ch to str
    strncat(str, &ch, 1);
 
    // print string
    printf("Appended String: %s\n", str);
 
    return 0;
}


Output: 

Original String: Geek
Character to be appended: s
Appended String: Geeks

 

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments