Martin McBride, 2017-02-12
Tags none
Categories none

A string is data type which is used to store text data.

Declaring a string

A string is usually enclosed in double quote characters. So you can declare a string like this:

STRING s = "Hello"

{{% purple-note %}} Some languages allow you to use single quotes instead. In that case, you can choose whichever you prefer. {{% /purple-note %}}

You can join strings together using the + operator:

STRING s = "Hello"
STRING w = "world"
STRING result = s + " " + w

This prints Hello world. The value in result is created from 3 strings, joined together by +:

  • s, which contains "Hello".
  • " ", a string which just contains one space character.
  • w, which contains "world".

String functions

Most languages provide various functions for dealing with strings. One of the most basic functions is the length function, which tells you how many characters there are in the string:

STRING s = "Hello"

prints 5, because "Hello" is 5 characters long.

You can search or match values:

string match

This can be useful, for example, to check a filename to find out what type of file it is (does it end in .jpg, .png. .mp3 etc).

You can also split strings, for example if you have some values separated by commas, the split function will split the text at each comma, and return each value as a separate string:

string split

As you can see, you can also join several strings together using any separator string you choose.

You can also do things like case conversion:

  • Use toupper() to convert "Hello world" into "HELLO WORLD".
  • Use tolower() to convert "Hello world" into "hello world".

Whatever programming language you learn, it is always worth getting to know the string functions!

A string is an array of characters

A string is usually stored as an array of characters. The string data is stored in consecutive memory locations, like this:


{{% yellow-note %}} Some languages store strings as ASCII values, so each character will occupy one byte. Other languages store strings as Unicode values, so each character will be stored as 2 bytes. {{% /yellow-note %}}

Accessing individual characters in a string

You can access the individual characters of a string using square brackets. Each character is numbered starting at 0 (as explained forarrays). For example:

STRING s = "Hello"
CHAR c = s[1]

In this code, we set c equal to the character at index 1 of the string s. Since the index starts at 0, element 1 is the second element, which is the character 'e'.


A substring is just a part of a string. For example in the string


you might want to extract the filename as a substring:


There is usually a function or some other way to extract a substring. The function takes 2 values - the start position of the substring, and its length.

Copyright (c) Axlesoft Ltd 2021