C Strings

What is a String?

In C, a string is a sequence of characters stored in an array.

Strings must end with a special character called the null terminator (\\0).

Loading...
Output:

String Initialization

You can initialize strings using double quotes.

The compiler automatically adds the null terminator.

Loading...
Output:

Printing Strings

Use printf with %s to print strings.

Loading...
Output:

Accessing Characters

Strings can be accessed like arrays using indexes.

Indexing starts at 0.

Loading...
Output:

Looping Through a String

You can loop through a string until you reach the null terminator.

Loading...
Output:

String Functions

The string.h library provides useful functions for working with strings.

Loading...
Output:

Common String Functions

Some important string functions include:

  • strlen() – get length
  • strcpy() – copy string
  • strcat() – concatenate strings
  • strcmp() – compare strings
Loading...
Output:

Modifying Strings

You can modify characters in a string if it is stored in an array.

Loading...
Output:

Strings and Pointers

Strings can also be represented using pointers.

However, modifying them may not always be allowed.

Loading...
Output:

Common Mistakes

Be careful with these:

  • Forgetting the null terminator
  • Buffer overflow (array too small)
  • Modifying string literals

Why Strings are Important

Strings are used in almost every program for handling text.

  • User input/output
  • File processing
  • Data manipulation

Practice

Create a string and print each character using a loop.

Loading...
Output:

Need Help?