String in C

By | February 15, 2023

In C programming language, a string is a sequence of characters that are stored in an array of characters. The string is terminated with a null character (‘\0’) which marks the end of the string.

In C, strings are stored as arrays of characters, and each character in the array represents a character in the string. For example, the string “hello” would be stored as an array of characters:

char string[] = {'h', 'e', 'l', 'l', 'o', '\0'};

or more commonly, it can be declared using double quotes as:

char string[] = "hello";

Strings can be manipulated in C using a number of built-in functions, such as strcpy(), strcat(), strlen(), strcmp(), etc.

Here are some basic operations that can be performed on strings in C:

  1. String declaration and initialization –
    char string1[20];           // declaration
    char string2[] = "hello";   // declaration and initialization
    
  2. String concatenation –
    char string1[] = "hello";
    char string2[] = "world";
    strcat(string1, string2);   // string1 now stores "helloworld"
    
  3. String comparison –
    char string1[] = "hello";
    char string2[] = "world";
    int result = strcmp(string1, string2);
    // if result is 0, strings are equal
    // if result is negative, string1 is less than string2
    // if result is positive, string1 is greater than string2
    
  4. String length –
    char string[] = "hello";
    int length = strlen(string); // length is 5
    

Note that in C, strings are null-terminated, which means that the null character marks the end of the string. This is important to keep in mind when manipulating strings, to avoid buffer overflow and other errors.

Please write comments below if you find anything incorrect, or you want to share more information about the topic discussed above. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.