In C++, strings are represented as arrays of characters, and can be manipulated using pointers and pointer arithmetic.
Here are some common string functions that use pointers:
strlen
: Calculates the length of a string
const char* str = "Hello, world!"; int length = 0; while (*str != '\0') { length++; str++; } cout << "Length: " << length << endl;
In this example, we define a character array str
and use a while loop to iterate through the string character by character. Using pointer arithmetic, we increment the pointer str
until we reach the end of the string (the null character \0
). We then print the length of the string to the console.
strcpy
: Copies a string to another string
const char* str1 = "Hello, world!"; char str2[50]; char* ptr = str2; while (*str1 != '\0') { *ptr = *str1; ptr++; str1++; } *ptr = '\0'; cout << "Copied string: " << str2 << endl;
In this example, we define a character array str1
and a character array str2
with enough space to hold the copied string. We also define a pointer ptr
and initialize it to point to the beginning of str2
.
Using a while loop, we iterate through str1
character by character and use pointer arithmetic to copy each character to str2
using the dereference operator (*
). Finally, we add the null character (\0
) to the end of str2
to terminate the string.
strcat
: Concatenates two strings
char str1[50] = "Hello, "; const char* str2 = "world!"; char* ptr = str1 + strlen(str1); while (*str2 != '\0') { *ptr = *str2; ptr++; str2++; } *ptr = '\0'; cout << "Concatenated string: " << str1 << endl;
In this example, we define a character array str1
and a character array str2
. We also define a pointer ptr
and initialize it to point to the end of str1
, using the strlen
function to calculate the length of str1
.
Using a while loop, we iterate through str2
character by character and use pointer arithmetic to copy each character to the end of str1
using the dereference operator (*
). Finally, we add the null character (\0
) to the end of str1
to terminate the concatenated string.
These are just a few examples of how pointers can be used to manipulate strings in C++. With pointers and pointer arithmetic, you can perform many other string operations as well.