Utilizor
Contact Us

CC Strings

Working with text.

C Strings

Strings are used for storing text/characters.

For example, "Hello World" is a string of characters.

Unlike many other programming languages, C does not have a string type to easily create string variables. Instead, you must use the char type and create an array of characters:

char greetings[] = "Hello World!";

Access Strings

Since strings are actually arrays in C, you can access a string by referring to its index number inside square brackets [].

Examples

Create String

c example

Printing a string.

#include <stdio.h>

int main() {
  char greetings[] = "Hello World!";
  printf("%s", greetings);
  return 0;
}

Access Character

c example

Accessing the first character.

#include <stdio.h>

int main() {
  char greetings[] = "Hello World!";
  printf("%c", greetings[0]);
  return 0;
}

Modify String

c example

Changing the first character.

#include <stdio.h>

int main() {
  char greetings[] = "Hello World!";
  greetings[0] = 'J';
  printf("%s", greetings);
  return 0;
}

Loop Through String

c example

Printing each character.

#include <stdio.h>

int main() {
  char carName[] = "Volvo";
  int i;
  
  for (i = 0; i < 5; ++i) {
    printf("%c\n", carName[i]);
  }
  return 0;
}

String Functions

c example

Using <string.h> functions.

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

int main() {
  char str1[] = "Hello";
  char str2[] = "World";
  
  // Concatenate
  strcat(str1, str2); 
  printf("%s\n", str1);

  // Copy
  strcpy(str1, str2);
  printf("%s\n", str1);
  
  // Length
  printf("%d", strlen(str1));
  
  return 0;
}

Test Your Knowledge

1. How do you create a string variable in C?

2. Which header file is needed for string functions?