Accessing String

Accessing String

Accessing String

In C++, Accessing string can be done in various ways. to access a single character of a string, you can use the indexing operator [] with the index of the character you want to access. The index of the first character in the string is 0. For example:

				
					std::string str = "Hello";

char first_char = str[0]; // first_char = 'H'

char second_char = str[1]; // second_char = 'e'

				
			

Modifying a single character:

You can also use the indexing operator [] to modify a single character of a string. For example:

				
					std::string str = "Hello";

str[0] = 'J';

// str = "Jello"
				
			

Iterating through a string:

You can iterate through a string using a for loop (we will see later) and the indexing operator []. For example:

				
					std::string str = "Hello";

for (int i = 0; i < str.length(); i++) {

    char current_char = str[i];

    // Do something with current_char

}


				
			

Note that in C++, a string is actually a class that contains many other useful functions for working with strings, such as length() to get the length of the string, substr() to extract a substring, and find() to search for a substring within the string.

Join To Get Our Newsletter
Spread the love