What is a 'string'?

A foundational guide to the string data type, one of the most basic building blocks in programming. Learn what a string is, how it's used to represent text, and some of the most common operations performed on it.

In the world of programming, we don't just work with numbers. We work with text. We need to store names, write messages, and process user input. The data type we use to represent this text is the string.

A string is, at its core, a sequence of characters. It's how virtually every programming language represents textual data.

Declaring a String

To create a string, you enclose a sequence of characters in quotes. Most languages support both single (') and double (") quotes.

In Python:

my_name = "Alice"
my_message = 'Hello, World!'

In C#:

string myName = "Alice";
// C# uses single quotes for a single character, not for strings.
// char myInitial = 'A';

In JavaScript:

let myName = "Alice";
let myMessage = 'Hello, World!';

Strings as Sequences

Because a string is a sequence of characters, you can often treat it like a list or an array. This allows you to perform several common operations.

Getting the Length

You can almost always get the number of characters in a string.

# Python
len(my_name) # 5
// C#
myName.Length; // 5

Accessing Characters by Index

You can access an individual character in a string using its zero-based index.

first_letter = my_name[0] # 'A'
char firstLetter = myName[0]; // 'A'

Common String Operations

Concatenation

Concatenation is the process of combining two or more strings into one. Most languages use the + operator for this.

first_name = "Alice"
last_name = "Smith"

full_name = first_name + " " + last_name # "Alice Smith"

Finding Substrings

Most languages provide methods to check if a string contains another string, or to find the position of a substring.

message = "Hello, World!"

'World' in message # True
message.find('World') # 7 (the index where 'World' starts)

String Immutability

In many popular languages, including Python, C#, and Java, strings are immutable. This is a very important concept. It means that once a string is created, it cannot be changed.

Any operation that appears to modify a string actually creates a new string in memory.

my_string = "Hello"

# This does not change the original string.
# It creates a new string "Hello, World!" and assigns it to the variable.
my_string = my_string + ", World!"

This immutability makes strings predictable and safe to use in many contexts, but it's something to be aware of when you are performing a large number of modifications, as it can have performance implications.

Conclusion

The string is one of the most fundamental data types in programming. It's the basis for all textual data manipulation. By understanding that a string is a sequence of characters and learning the common operations like concatenation and indexing, you master a core building block that you will use every single day as a software developer.