What is a String?

A string is an array of characters ending with a null character \0.

Example:

char name[] = “Alice”;

Equivalent to:

char name[] = {‘A’,’l’,’i’,’c’,’e’,’\0′};

String Input and Output:

char name[20];

scanf(“%s”, name);

printf(“Hello %s”, name);

  • scanf() does not read spaces. Use gets() / fgets() if spaces are needed.
  • Common String Functions (from <string.h>):

Function

Purpose

Example

strlen()

Returns length of string

strlen(“Hello”) → 5

strcpy()

Copies one string to another

strcpy(str2, str1)

strcmp()

Compares two strings

strcmp(s1, s2)

strcat()

Concatenates (joins) two strings

strcat(s1, s2)

 

Difference: Character Array vs String

Character Array

String Literal

char name[5] = {‘A’,’B’,’C’,’\0′};

char name[] = “ABC”;

Needs \0 manually

Adds \0 automatically