The Java String charAt function is a method that returns the character at a specified index position within a string. The index position starts at 0 for the first character in the string and increases by 1 for each subsequent character. The charAt function takes an integer argument that represents the index position of the desired character. If the index is out of range, the function will throw an IndexOutOfBoundsException. The returned value is a single character, which can be stored in a char variable or used in other operations. This function is useful for accessing and manipulating individual characters within a string. Keep reading below to learn how to Java String charAt in C++.

Looking to get a head start on your next software interview? Pickup a copy of the best book to prepare: Cracking The Coding Interview!

Buy Now On Amazon

Java String charAt in C++ With Example Code

Java’s String class has a method called charAt() that returns the character at a specified index in a string. This method can be useful when working with strings in Java, but what if you’re working with C++? Fortunately, C++ has a similar function that can be used to achieve the same result.

The C++ function that is equivalent to Java’s charAt() method is the string::at() function. This function takes an index as an argument and returns the character at that index in the string. Here’s an example:


using namespace std;

int main() {
string str = "Hello, world!";
char c =;
cout << c << endl; return 0; }

In this example, we create a string called "str" and assign it the value "Hello, world!". We then use the at() function to retrieve the character at index 4 (which is the fifth character in the string, since indexing starts at 0). The character is stored in a variable called "c", which we then print to the console.

It's worth noting that the at() function throws an out_of_range exception if the index is out of bounds. This means that you should always make sure that the index you're using is within the bounds of the string before calling the function.

In summary, if you're looking for a way to retrieve a specific character from a string in C++, you can use the string::at() function. This function works in a similar way to Java's charAt() method and can be a useful tool when working with strings in C++.

Equivalent of Java String charAt in C++

In conclusion, the equivalent function of Java's String charAt() in C++ is the string's operator[]. This function allows us to access a specific character in a string by its index. It is important to note that the index starts at 0 in C++, just like in Java. Additionally, the operator[] function in C++ is faster than the charAt() function in Java, making it a more efficient option for accessing characters in a string. Overall, understanding the equivalent function in C++ can be helpful for Java developers who are transitioning to C++ or working on projects that require knowledge of both languages.

Contact Us