Meganathan
Meganathan

Reputation: 1

How to find the last character of an string and assign it to a char pointer?

I need Ptr to have first character of the string and BufLim to have last character of the string.

#include <iostream>
using namespace std;

int main()
{
    const char* Str = "Stackoverflow";
    const char* Ptr = Str[0];
    const char* BufLim = &Ptr.back(); // pointer pointing to last character of *ptr

    cout << Ptr;
    cout << BufLim;
    return 0;
}

Kindly help me on this.

Upvotes: 0

Views: 1138

Answers (1)

JeJo
JeJo

Reputation: 32847

Prior to , use std::string instead of const char* string literals. Then you can easily have the pointer to the first and the last char of the string by the help of member functions std::string::front and std::string::back respectively (given that the string is not empty).

#include <string>
using namespace std::string_literals;

std::string Str{ "Stackoverflow"s };
/* const */ char* ptrFirst = &Str.front();
/* const */ char* ptrLast = &Str.back();
std::cout << *ptrFirst << "\n";  // prints S
std::cout << *ptrLast;           // prints w

(Alternatively) in , you can use std::string_view, which is basically a wrapper around const char*. Like std::string, it has the same kind of member functions std::string_view::front and std::string_view::back

#include <string_view>
using namespace std::string_view_literals;

std::string_view Str{ "Stackoverflow"sv };
const char* ptrFirst = &Str.front();
const char* ptrLast = &Str.back();
std::cout << *ptrFirst << "\n";   // prints S
std::cout << *ptrLast;            // prints w

Upvotes: 3

Related Questions