+ 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?

3rd May 2020, 4:01 AM
Ashfaq Reshad
Ashfaq Reshad - avatar
4 odpowiedzi
+ 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
3rd May 2020, 4:07 AM
Ipang
+ 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
3rd May 2020, 4:07 AM
Arsenic
Arsenic - avatar
+ 2
Thanks everyone❤
3rd May 2020, 4:30 AM
Ashfaq Reshad
Ashfaq Reshad - avatar
+ 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; }
3rd May 2020, 4:14 AM
ChaoticDawg
ChaoticDawg - avatar