Categories
d. Strings

C strcmp()

The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.

C strcmp() Prototype

The function prototype of strcmp() is:

int strcmp (const char* str1, const char* str2);

strcmp() Parameters

The function takes two parameters:

  • str1 – a string
  • str2 – a string

Return Value from strcmp()

Return ValueRemarks
0if strings are equal
>0if the first non-matching character in str1 is greater (in ASCII) than that of str2.
<0if the first non-matching character in str1 is lower (in ASCII) than that of str2.

The strcmp() function is defined in the string.h header file.

Example: C strcmp() function

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

int main() {
  char str1[] = "abcd", str2[] = "abCd", str3[] = "abcd";
  int result;

  // comparing strings str1 and str2
  result = strcmp(str1, str2);
  printf("strcmp(str1, str2) = %d\n", result);

  // comparing strings str1 and str3
  result = strcmp(str1, str3);
  printf("strcmp(str1, str3) = %d\n", result);

  return 0;
}

Output

strcmp(str1, str2) = 1
strcmp(str1, str3) = 0

In the program,

  • strings str1 and str2 are not equal. Hence, the result is a non-zero integer.
  • strings str1 and str3 are equal. Hence, the result is 0.
Categories
d. Strings

C strcat()

In C programming, the strcat() function contcatenates (joins) two strings.

The function definition of strcat() is:

char *strcat(char *destination, const char *source)

It is defined in the string.h header file.

strcat() arguments

As you can see, the strcat() function takes two arguments:

destination – destination string
source – source string

The strcat() function concatenates the destination string and the source string, and the result is stored in the destination string.

Example: C strcat() function

#include <stdio.h>
#include <string.h>
int main() {
   char str1[100] = "This is ", str2[] = "programiz.com";

   // concatenates str1 and str2
   // the resultant string is stored in str1.
   strcat(str1, str2);

   puts(str1);
   puts(str2);

   return 0;
}

Output

This is programiz.com
programiz.com

Note: When we use strcat(), the size of the destination string should be large enough to store the resultant string. If not, we will get the segmentation fault error.

Categories
d. Strings

C strcpy()

C strcpy()

The function prototype of strcpy() is:

char* strcpy(char* destination, const char* source);
  • The strcpy() function copies the string pointed by source (including the null character) to the destination.
  • The strcpy() function also returns the copied string.

The strcpy() function is defined in the string.h header file.


Example: C strcpy()

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

int main() {
  char str1[20] = "C programming";
  char str2[20];

  // copying str1 to str2
  strcpy(str2, str1);

  puts(str2); // C programming

  return 0;
}

Output

C programming

Note: When you use strcpy(), the size of the destination string should be large enough to store the copied string. Otherwise, it may result in undefined behavior.

Categories
d. Strings

C strlen()

The strlen() function calculates the length of a given string.

The strlen() function takes a string as an argument and returns its length. The returned value is of type size_t (the unsigned integer type).

It is defined in the <string.h> header file.

Example: C strlen() function

#include <stdio.h>
#include <string.h>
int main()
{
    char a[20]="Program";
    char b[20]={'P','r','o','g','r','a','m','\0'};

    // using the %zu format specifier to print size_t
    printf("Length of string a = %zu \n",strlen(a));
    printf("Length of string b = %zu \n",strlen(b));

    return 0;
}

Output

Length of string a = 7
Length of string b = 7

Note that the strlen() function doesn’t count the null character \0 while calculating the length.

Categories
d. Strings

String Manipulations In C Programming Using Library Functions

You need to often manipulate strings according to the need of a problem. Most, if not all, of the time string manipulation can be done manually but, this makes programming complex and large.

To solve this, C supports a large number of string handling functions in the standard library "string.h".

Few commonly used string handling functions are discussed below:

FunctionWork of Function
strlen()computes string’s length
strcpy()copies a string to another
strcat()concatenates(joins) two strings
strcmp()compares two strings
strlwr()converts string to lowercase
strupr()converts string to uppercase

Strings handling functions are defined under "string.h" header file.

#include <string.h>

Note: You have to include the code below to run string handling functions.

gets() and puts()

Functions gets() and puts() are two string functions to take string input from the user and display it respectively as mentioned in the previous chapter.

#include<stdio.h>

int main()
{
    char name[30];
    printf("Enter name: ");
    gets(name);     //Function to read string from user.
    printf("Name: ");
    puts(name);    //Function to display string.
    return 0;
}

Note: Though, gets() and puts() function handle strings, both these functions are defined in "stdio.h" header file.

Categories
d. Strings

Programming Strings

In C programming, a string is a sequence of characters terminated with a null character \0. For example:

char c[] = "c string";

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

Memory diagram of strings in C programming
Memory Diagram

How to declare a string?

Here’s how you can declare strings:

char s[5];
string declaration in C programming
String Declaration in C

Here, we have declared a string of 5 characters.

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', '\0'};

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

Let’s take another example:

char c[5] = "abcde";

Here, we are trying to assign 6 characters (the last character is '\0') 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.

Also notice that we have used the code name instead of &name with scanf().

scanf("%s", name);

This is because name is a char array, and we know that array names decay to pointers in C.

Thus, the name in scanf() already points to the address of the first element in the string, which is why we don’t need to use &.

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
}