Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get last character of string in c++? [duplicate]

Tags:

c++

string

In python you can say print "String"[-1] and it would print be the last character, 'g'. Is there an equivalent for this in c++?

like image 297
hamza Avatar asked Sep 04 '15 05:09

hamza


People also ask

How do you get the last character of a string?

If we want to get the last character of the String in Java, we can perform the following operation by calling the "String. chatAt(length-1)" method of the String class. For example, if we have a string as str="CsharpCorner", then we will get the last character of the string by "str. charAt(11)".

How do you find the last occurrence of a character in a string in C?

The strrchr() function finds the last occurrence of c (converted to a character) in string . The ending null character is considered part of the string . The strrchr() function returns a pointer to the last occurrence of c in string . If the given character is not found, a NULL pointer is returned.

How do you compare the last part of a string?

If you have a pointer-to-char array, str , then this: int len = strlen(str); const char *last_four = &str[len-4]; will give you a pointer to the last four characters of the string. You can then use strcmp() .

How do I copy a character from one string to another?

Copying one string to another - strcpystrcpy can be used to copy one string to another. Remember that C strings are character arrays. You must pass character array, or pointer to character array to this function where string will be copied. The destination character array is the first parameter to strcpy .


1 Answers

You can use string.back() to get a reference to the last character in the string. The last character of the string is the first character in the reversed string, so string.rbegin() will give you an iterator to the last character.

like image 180
David Schwartz Avatar answered Sep 21 '22 18:09

David Schwartz