top

Search

C Tutorial

.

UpGrad

C Tutorial

C string declaration

Following their ease of conveying information from program to user, Strings play a crucial role in C programming. You can implement strings in C using character arrays, enabling you to perform standard operations. Alternatively, you can implement strings using pointers because character arrays behave as pointers. 

Before going through the details of C string declaration, let’s first get an overview of a string.

Understanding a String

A string refers to a collection of characters (including numerals, symbols, letters and punctuations) represented in a regular, uniform sequence. A string in C is a sequence of characters terminated with a NULL character '\0'.

Here’s an example of C string declaration.

char str[] = "Programming.\0";

Strings in C are enclosed within double quotes(" "), and characters are enclosed within single quotes(' '). Whenever the compiler detects a sequence of characters enclosed with double quotes marks, by default, it adds a null character (\0) at the end.

A string literal means a sequence comprising zero or multiple multibyte characters enclosed within double quotes. For example, "language". 

Significance of C strings

The following points justify the importance of C strings:

  • Efficiently represents textual data

  • Provides standard library support

  • Increases a C program’s efficiency and flexibility

  • Provides compatibility and interoperability

  • Supports various input/output operations

  • Supports data processing and manipulation

  • Easy access and processing of command-line arguments and parameters

Initialising C Strings

Here are the four methods to initialise a string under C programming:

  • Assign a string literal with size

  • Assign a string literal without size

  • Assign character by character with size

  • Assign character by character without size

1. Assign a string literal with size

A string literal can be assigned to any character array. Make sure that the array’s size is one more compared to the string literal length. For example, if you want to store a string of size n, the array’s size should be- n+1.

Here is a typical string in C example. 

char str[10] = "Software.";

Although the string length is 9, we set the size to 10 to accommodate Null Character. The compiler automatically adds the Null character(\0) while closing. If the array of strings in C can’t accommodate the whole string, it only receives characters according to its space. Let’s look at the following example to understand it: 

char str[3] = "Software.";
printf("%s",str);

 Output:

Sof

As seen in the example above, the defined length of the array is 3, so the program only prints the first three elements.

2. Assign a string literal without size

You can directly allot a string literal to any character array without specifying the size, as the compiler determines the size during compile time automatically. Here’s how.

char str[] = "Software.";

In the above example, the size is not defined. Here, "str" behaves as a pointer since it is an array. 

3. Assign character by character with size

You can assign a string based on each character. But make sure to terminate the last character with '\0'. Here’s an example:

char str[10] = {'S', 'o', 'f', 't', 'w', 'a', 'r', 'e' ,'.','\0'};

 4. Assign character by character without size

You can allot each character with the null character while closing. The compiler will automatically determine the string’s size

char str[] = {'S', 'o', 'f', 't', 'w', 'a', 'r', 'e' '.','\0'};

 Accessing C Strings

The process of accessing C strings incorporates retrieving and manipulating individual characters from a null-terminated character array. A few common ways to access C strings are:

  • Accessing individual characters

  • Modifying characters

  • Iterating over a string

Declaration of C Strings

The data type of string in C is character.  C doesn’t directly support string as a data type. Thus,  you should use character arrays to display a string in C. Here’s the syntax of C string declaration:

char variable[array_size];

Based on this syntax, let’s declare the strings.

char str[10];

String Literal Declaration

A string literal in C refers to a sequence of characters contained in double quotation marks (" "). For example,

char* str = "We are programmers.";

Character Array Declaration

A character array indicates a continuous sequence of characters, usually terminated by a null character ('\0'). In C, you can declare and use character arrays as follows:

char str1[] = {'L', 'e', 'a', 'r', 'n', 'i', 'n', 'g', '\0'};

 Pointer Declaration

In C, pointers are variables that hold memory addresses. The following syntax helps you to declare and use pointers in C:

int num = 42;
int* ptr;
ptr = #

Reading and Writing C Strings

Reading C Strings

If you want to read strings in C, you can use the scanf function or its safer alternative, fgets. The scanf function lets you read input from the standard input stream. Its syntax is:


The fgets function reads a line of input from any standard input stream and saves it in a character array. Here’s its syntax.
scanf("%s", str);
fgets(str, sizeof(str), stdin);

Writing C Strings

If you want to write or output C strings, you can use the printf function or any other output functions such as fputs or puts.
Syntax of printf function:



Syntax of printf function:
printf("String: %s\n", str);


Syntax of puts function:
puts(str);


Syntax of fputs function:

fputs(str, stdout);

String Input using scanf()

The scanf() is used for string input in C. It reads a sequence of characters up till it detects whitespace (like tab, space, newline, etc.).  The following example demonstrates how scanf string in C works. 

char str[40];
    printf("Enter a string: ");
    scanf("%s", str);

    printf("You entered: %s\n", str);

 Suppose we provide the given input:

We are learning C programming

 We get the output:

We

As seen from the above example, the scanf() function stops accepting input if it encounters whitespace. %s refers to a format specifier used to accept input and display output strings in C.

String Manipulation Functions

 • strlen() Function

The strlen() function returns the length of a string without the null character ('\0').


 • strcat() Function

This function appends one string to the termination of another.


 • strcpy() Function

It copies the data of one string to another.


• strcmp() Function

This function draws a comparison between two strings lexicographically. If the first string is greater compared to the second one, it returns a positive value, 0 if both strings are equal, and a negative value if the initial string is smaller than the second one.

Reading a Line of Text

The scanf() function can’t read strings with spaces because it halts the reading process automatically whenever it detects whitespace. If you want to read and print strings comprising whitespace, you can use the fgets() and puts() functions.

fgets():

This function reads a specific number of characters. It is declared as:

fgets(name_of_string, number_of_characters, stdin);

Let’s understand each parameter of the above syntax.

name_of_string*: It refers to the variable that stores the string.

number_of_characters: It specifies the maximum length of the string that must be read.

stdin: It is the file handle from where the string will be read.

 

puts():

It is used to display strings. Here’s its syntax.

puts(name_of_string);

Here, name_of_string is the variable to store the string.

 

The following example program uses both the above string functions in C with examples.

#include <stdlib.h>
#include <stdio.h>
 
int main() 
{
  char str[40];
  printf("Please enter a string: ");
  fgets(str, sizeof(str), stdin);
  printf("The entered string is: ");
  puts(str);
 
  return 0;
}

 Input:

Please enter a string: I am a lucky person

Output:

The entered string is: I am a lucky person

As seen from the above example, the input string has the whitespace. However, the combination of fgets() and puts() functions lets the program store and display the whole string.

Passing strings to functions

The strings are merely character arrays. So, you can pass strings to function the way you pass an array to a function. You can do this either using a pointer or an array. Here’s an example program that demonstrates how to pass strings to functions.

#include <stdio.h>
 
void pointer(char * str) 
{
  printf("The input string is : ");
  puts(str);
  printf("\n");
}
 
void array(char str[]) 
{
  printf("The input string is : ");
  puts(str);
  printf("\n");
}
 
int main() 
{
 
  char str[30] = "I like C programming";
  pointer(str);
  array(str);
  return 0;
}

 Output:

The string is : I like C programming
The input string is : I like C programming

As seen from the above example, the string str is passed to an array and also to a pointer.

Pointers and Strings

The strings in C are depicted using character arrays acting as pointers. So, you can use pointers to perform string operations. 

#include <stdlib.h>
#include <stdio.h>
 
int main() 
{
char str[] = "Software.";
printf("%c", *str); // gives output: S
printf("%c", *(str + 1)); // gives output: o
printf("%c\n", *(str + 8)); // gives output: .
 
char * stringPtr;
stringPtr = str;
printf("%c", *stringPtr); // Output: S
printf("%c", *(stringPtr + 1)); // Output: o
printf("%c", *(stringPtr + 8)); // Output: .
 
return 0;
}

Output:

So.
So.

 String Example in C

The following program illustrates how C handles string literals using arrays and pointers. 

#include <stdio.h>
 
void array(char str[]) 
{
 
  printf("Now we will look at how C handles string literals using array.\n");
 
  printf("First character : %c\n", str[0]);
 
 printf("Second character : %c\n", str[1]);
 
  printf("The whole input string is : %s\n", str);
  str[0] = 'M'; //the command assigns the first element of the array to M.
 
  printf("The newly entered string is : %s\n", str);
}
 
void literal(char * str)
{
 
  printf(" Now we will look at how C handles string literals using pointers.\n");
 
  printf("First character is: %c\n", str[0]);
 
  printf("Second character is: %c\n", str[1]);
 
  printf("The whole input string is : %s\n", str);
  // str[0] = 'N';
  //the command tries assigning the first element of the array to N but it's not allowed with string literals because they are saved on the read-only memory.
}
 
int main() 
{
  char str[] = "Software."; //the command assigns the string literal to a character array.
  array(str);
  printf("\n");
 
  char * strPntr = "Software."; //the command assigns the string literal to a pointer.
  literal(strPntr);
 
  return 0;
}

Output: 

Now we will look at how C handles string literals using array.
First character : S
Second character : o
The whole input string is : Software.
The newly entered string is : Moftware.
 
Now we will look at how C handles string literals using pointers.
First character is: S
Second character is: o
The whole input string is : Software.

 When C handles the string literal using an array, it displays the whole input string. Also, it allows the substitution of elements of the array. When C handles string literal using a pointer, it, too, displays the whole input string. However, it doesn’t allow the substitution of characters.

Character Array and String Literal: Differences

Character Array

String Literal

The declaration of character arrays involves specifying char data type followed by the array name and size.

The declaration of string literals happens by enclosing the sequence of characters in double quotation marks.

Character arrays are mutable, so you can alter individual characters in the array.

Typically, string literals are stored in read-only memory and are immutable. If you directly try to alter a string literal, it may lead to undefined behaviour.

Character arrays are either allocated on the stack or dynamically allocated through malloc or associated functions. Hence, they increase the flexibility of memory management. 

String literals are stored in read-only memory, usually in a compiler-managed data segment.

Character arrays should be explicitly null-terminated by specifying a null character ('\0') at the end of the string.

String literals are automatically null-terminated.

You can explicitly specify the size of a character array. Hence, you can control the memory allocated for the particular string. 

String literals' sizes are automatically decided as per the length of the enclosed string (including the null character).


Applications of C Strings

Here are a few common applications of C Strings

  • Input and output operations

  • String storage and management

  • Text processing and manipulation

  • File manipulation

  • Command-line arguments and parameters

  • Data exchange and interoperability

  • Text-based user interfaces

To Sum Up

Strings in C simplify accessing, manipulating, and storing information. They improve the efficiency of compile-time allocation. Moreover, they provide the easiest possible storage that conserves space.

Understanding the basics of string in C is not adequate, as you also need to practice it and try applying it in different scenarios. Adopting this approach will help you master all essential concepts of string in C.

While going through tutorials to strengthen your fundamentals, you can enrol in upGrad’s Master of Science in Computer Science program, offered by Liverpool John Moores University and skyrocket your software development career. It lets you learn software development using various programming languages, helping you excel in the field of development!

FAQs

Q. How can you pass a string to functions in C?

You can pass a string to functions as a pointer or a character array.

Q. What is the limitation while reading a string in C?

The scanf() function reads strings in C, but it only reads until it runs into whitespace.

Q. What are string manipulation functions?

The string manipulation functions help you to compare or manipulate strings. They have the str prefix. Some of the examples of these functions are strlen(), strcat(), strcmp(), strcpy(), stricmp(), strchr(), etc.

Leave a Reply

Your email address will not be published. Required fields are marked *