geeksforgeeks

geeksforgeeks-Array-Reverse a St

2017-08-16  本文已影响22人  AlanMa

Given a string S as input. You have to reverse the given string.

Input: First line of input contains a single integer T which denotes the number of test cases. T test cases follows, first line of each test case contains a string S.

Output: Corresponding to each test case, print the string S in reverse order.

Constraints:

1<=T<=100
3<= length(S) <=1000

Example:

Input:
3
Geeks
GeeksforGeeks
GeeksQuiz

Output:
skeeG
skeeGrofskeeG
ziuQskeeG

C++代码

#include <iostream>
#include <cstring>
using namespace std;

int main() {
    //code
    //get the number of op times
    int T;
    cin>>T;
    
    for(int i=0; i<T; i++)
    {
        //get the string
        char str[30];
        cin.getline(str, 30);
        int len = strlen(str);//get the str length
        cout<<len;
        int end = len - 1;
        int start = 0;
        char tmp;
        while(start<end)
        {
            tmp = str[start];
            str[start] = str[end];
            str[end] = tmp;
            
            start += 1;
            end -= 1;
        }
        
        for(int j=0; j<len; j++)
        {
            cout<<str[j];
        }
        //cout<<endl;
        
    }
    return 0;
}

第二版
注意:

#include <bits/stdc++.h>
using namespace std;

int main() {
    //code
    //get the number of op times
    int T;
    cin>>T;
    //advoid read the '\n'
    cin.ignore(100, '\n');  
    while(T--)
    {
        //get the string
        //char str[30];
        //cin.getline(str, 30);
        ////or
        string str;
        getline(cin,str);
        int len = str.length();//get the str length
        
        //int len = strlen(str);//get the str length
        for(int i=0; i<len/2; i++)
        {
            swap(str[i],str[len-i-1]);
        }
        /*
        for(int j=0; j<len; j++)
        {
            cout<<str[j];
        }
        */
        cout<<str<<endl;
        
    }
    return 0;
}

python代码

#code
def reverse_string(str):
    reverse_str = str[::-1]
    
    return reverse_str
    

# get the number of op times
T = int(input())

for i in range(0,T):
    # get the string
    str = input()
    reverse_str = reverse_string(str)

    # print string
    print(reverse_str)
上一篇下一篇

猜你喜欢

热点阅读