It's quite easy actually. You just need to iterate the string starting from the end and finishing at the place 0 of the string. Also, you need to have another string variable for saving each element.
Pseudocode (sort of)
declare stringa
declare stringb
strinb = stringa
for i = length of stringa-1 i>=0 i decreases by one
stringb element in place length of stringb - 1 = stringa element in place i
output stringb
Here it is in C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
|
#include<iostream>
#include<string>
using namespace std;
string reverse(string str){
int len = str.size()-1; //the size of the array, i just put it in a variable to clear the code
string temp=str; //declare a temporary string
for (int i=len; i>=0; i--){
temp[len-i]=str[i]; //here, i starts from the end of the string, finishes at 0. So,
//when i = len, then len-i=0 So temp[0] = temp[len]
//first equals final. the second equals second from the end
//and so on
}
return temp;
}
int main(){
string input;
getline(cin, input);
cout<<reverse(input);
}
|
Now, assign a string to an array:
Strings are already 1D arrays of characters. If I understood correctly, you need an array of strings, right? So this s a 2D array. This can be done easily, example below:
Example: Make a program which gets as an input in the first line an integer N (number of students) and then a number K<N which defines which student in the list to output. After, N lines, each of a name of a student. This is a simple array problem. If it was with integers, not names it would be:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
|
#include<iostream>
using namespace std;
int main(){
int n;
cin>>n;
int place;
cin>>place;
int arr[n];
for (int i=0; i<n; i++){
cin>>arr[i];
}
cout<<arr[place-1]; //-1 because of the index starting from 0
}
|
With strings it's quite similar:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
|
#include<iostream>
#include<strings>
using namespace std;
int main(){
int n;
cin>>n;
int place;
cin>>place;
string names[n]; //declare an array of strings
for (int i=0; i<n; i++){
cin>>names[i];
}
cout<<names[place-1];
}
|
If you want to acces a letter of a string in a string array, such as the student's first letter: