C programming tutorials for Beginners – C Programming Strings

(C Programming Tutorials)

C Programming Strings

In this tutorial, you’ll learn about strings in C programming. You’ll learn to declare them, initialize them and use them for various I/O operations with the help of examples.

char c[] = "c string";

When the compiler encounters a sequence of characters enclosed in the double quotation marks, it appends a null character  at the end by default.

Memory diagram of strings in C programming

How to declare a string?

Here’s how you can declare strings:

char s[5];
string declaration in C programming

Sign up to get end-to-end “Learn By Coding” examples and tutorials for Beginners.


 

How to initialize strings?

You can initialize strings in a number of ways.

char c[] = "abcd";

char c[50] = "abcd";

char c[] = {'a', 'b', 'c', 'd', ''};

char c[5] = {'a', 'b', 'c', 'd', ''};
Initialization of strings in C programming

Let’s take another example:

char c[5] = "abcde";

Here, we are trying to assign 6 characters (the last character is '') to a char array having 5 characters. This is bad and you should never do this.


Assigning Values to Strings

Arrays and strings are second-class citizens in C; they do not support the assignment operator once it is declared. For example,

char c[100];
c = "C programming";  // Error! array type is not assignable.

Note: Use the strcpy() function to copy the string instead.


Read String from the user

You can use the scanf() function to read a string.

The scanf() function reads the sequence of characters until it encounters whitespace (space, newline, tab, etc.).


Example 1: scanf() to read a string

#include <stdio.h>
int main(){
    char name[20];
    printf("Enter name: ");
    scanf("%s", name);
    printf("Your name is %s.", name);
    return 0;
}

Output

Enter name: Dennis Ritchie
Your name is Dennis.

Even though Dennis Ritchie was entered in the above program, only “Dennis” was stored in the name string. It’s because there was a space after Dennis.


How to read a line of text?

You can use the fgets() function to read a line of string. And, you can use puts() to display the string.


Example 2: fgets() and puts()

#include <stdio.h>
int main(){
    char name[30];
    printf("Enter name: ");
    fgets(name, sizeof(name), stdin);  // read string
    printf("Name: ");
    puts(name);    // display string
    return 0;
}

Output

Enter name: Tom Hanks
Name: Tom Hanks

Here, we have used fgets() function to read a string from the user.

fgets(name, sizeof(name), stdlin); // read string

The sizeof(name) results to 30. Hence, we can take a maximum of 30 characters as input which is the size of the name string.

To print the string, we have used puts(name);.

Note: The gets() function can also be to take input from the user. However, it is removed from the C standard.

It’s because gets() allows you to input any length of characters. Hence, there might be a buffer overflow.


Passing Strings to Functions

Strings can be passed to a function in a similar way as arrays. Learn more about passing arrays to a function.


Example 3: Passing string to a Function

#include <stdio.h>
void displayString(char str[]);

int main(){
    char str[50];
    printf("Enter string: ");
    fgets(str, sizeof(str), stdin);             
    displayString(str);     // Passing string to a function.    
    return 0;
}
void displayString(char str[]){
    printf("String Output: ");
    puts(str);
}

Strings and Pointers

Similar like arrays, string names are “decayed” to pointers. Hence, you can use pointers to manipulate elements of the string. We recommended you to check C Arrays and Pointers before you check this example.


Example 4: Strings and Pointers

#include <stdio.h>

int main(void){
  char name[] = "Harry Potter";

  printf("%c", *name);     // Output: H
  printf("%c", *(name+1));   // Output: a
  printf("%c", *(name+7));   // Output: o

  char *namePtr;

  namePtr = name;
  printf("%c", *namePtr);     // Output: H
  printf("%c", *(namePtr+1));   // Output: a
  printf("%c", *(namePtr+7));   // Output: o
}

Commonly Used String Functions

  • strlen() – calculates the length of a string
  • strcpy() – copies a string to another
  • strcmp() – compares two strings
  • strcat() – concatenates two strings

 

Personal Career & Learning Guide for Data Analyst, Data Engineer and Data Scientist

Applied Machine Learning & Data Science Projects and Coding Recipes for Beginners

A list of FREE programming examples together with eTutorials & eBooks @ SETScholars

95% Discount on “Projects & Recipes, tutorials, ebooks”

Projects and Coding Recipes, eTutorials and eBooks: The best All-in-One resources for Data Analyst, Data Scientist, Machine Learning Engineer and Software Developer

Topics included: Classification, Clustering, Regression, Forecasting, Algorithms, Data Structures, Data Analytics & Data Science, Deep Learning, Machine Learning, Programming Languages and Software Tools & Packages.
(Discount is valid for limited time only)

Disclaimer: The information and code presented within this recipe/tutorial is only for educational and coaching purposes for beginners and developers. Anyone can practice and apply the recipe/tutorial presented here, but the reader is taking full responsibility for his/her actions. The author (content curator) of this recipe (code / program) has made every effort to ensure the accuracy of the information was correct at time of publication. The author (content curator) does not assume and hereby disclaims any liability to any party for any loss, damage, or disruption caused by errors or omissions, whether such errors or omissions result from accident, negligence, or any other cause. The information presented here could also be found in public knowledge domains.

Learn by Coding: v-Tutorials on Applied Machine Learning and Data Science for Beginners

Please do not waste your valuable time by watching videos, rather use end-to-end (Python and R) recipes from Professional Data Scientists to practice coding, and land the most demandable jobs in the fields of Predictive analytics & AI (Machine Learning and Data Science).

The objective is to guide the developers & analysts to “Learn how to Code” for Applied AI using end-to-end coding solutions, and unlock the world of opportunities!