+ 1
How can i print only the first & last letter of a string?
suppose a string is "localization" ; how can i print only l & n?
4 Answers
+ 3
std::string str {"localization"};
std::cout << str.front() << " " << str.back();
Reference:
https://en.cppreference.com/w/cpp/string/basic_string/front
https://en.cppreference.com/w/cpp/string/basic_string/back
+ 2
String is nothing but an array of characters. You can access any element just like you do in an array.
For example in "localisation" 'l' is just str[0].
or
if you are using std::strings then just like Ipang told, you can also use front() and back() to get the front and back of the string
+ 2
Thanks everyoneâ€
+ 1
If for some reason you need to you can also convert the string to a C string char array.
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
string s = "localization";
int l = s.length();
char ch_arr[l+1];
strcpy(ch_arr, s.c_str());
cout << ch_arr[0] << " " << ch_arr[l-1];
return 0;
}