如何用 Python 和 C 實現字元反轉? 字串反序輸出?

2020-08-11 23:36:43

給定一個字串,然後將其翻轉,逆序輸出

一. Python

1.字串切片

s = "123ABC"
s = s[::-1]
print(s)
def invert(x):
    return x[::-1]
print(invert("123ABC"))

2.reverse

s="123ABC"
print("".join(reversed(s)))
s = "123ABC"
l = list(s)
l.reverse()
print("".join(l))
s = "123ABC"
l = list(s)
print("".join(l[::-1]))

3.reduce

s="123ABC"
from functools import reduce
result = reduce(lambda x,y:y+x,s)
print(result)

//Python3 ,這個函數從全域性名稱空間中移除,放在了 functools模組

4.遞回函數

s="123ABC"
def func(s):
    if len(s) <1:
        return s
    return func(s[1:])+s[0]
result = func(s)
print(result)

5. 棧

s="123ABC"
def func(s):
    l = list(s) #模擬全部入棧
    result = ""
    while len(l)>0:
        result += l.pop() #模擬出棧
    return result
result = func(s)
print(result)

6.for回圈

s = "123ABC"
print("".join([s[-i] for i in range(1, len(s) + 1)]))
s="123ABC"
def func(s):
    result = ""
    max_index = len(s)-1
    for index,value in enumerate(s):
        result += s[max_index-index]
    return result
result = func(s)
print(result)

二.C語言

1.

#include<stdio.h>

int main(int c, char **v)
{
    return ((c = getchar()) != '\n') ? (main(c, v), putchar(c)) : 0;
}

2.

#include "stdio.h"
#include "string.h"
int main(void){
    char s[]="1234567890abcdefghijklmnopqrstuvwxyz";
    printf("%s\n",strrev(s));
    return 0;
}

3.

#include <stdio.h>
#include <string.h>
char a[110];
void convert(char a[],int n);
int main()
{
	scanf("%s",a);
	convert(a,strlen(a));
	printf("%s\n",a);
	return 0;
}
void  convert(char a[],int n)
{
	int len=n/2;
	for(int i=0;i<len;++i)
	{
		char t=a[i];
		a[i]=a[n-1-i];
		a[n-1-i]=t;
	}
}

4.

#include <stdio.h>
#include <string.h>

void rev(char *buf, int size)
{
        int i = 0;
        int temp;
        for(;i<size/2; i++)
        {

                temp = buf[i];
                buf[i] = buf[size-i-1];
                buf[size-i-1] = temp;
        }
}

int main()
{
    char str[20] = "hello world!";
    int size;

    size = strlen(str);

    printf("%s\n", str);

    rev(str, size);
    printf("%s\n", str);

    return 0;
}

5.

#include "stdio.h"
#include "string.h"
#include "math.h"

void reverse(char *str)
{
    int length = strlen(str);

    for (length; length > 0; length--)
    {
        printf("%c", *(str + length - 1));
    }
}

int main(void)
{
    char str[1024] = {};

    printf("請輸入一行字串:");
    //這裏不用scanf()是因爲scanf()一次只能讀取一個連續字串,遇到空格則會捨棄空格後的其他字元
    fgets(str, 1024, stdin);

    reverse(str);

    return 0;
}

6.

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

void show(string::iterator _begin, string::iterator _end)
{
    if(_begin <= _end)
    {
        cout << *_end << endl;
        show(_begin, --_end);
    }
}

void reverse(string &s)
{
    show(s.begin(), --s.end());
}

int main()
{
    string s("ABCDEFG");
    reverse(s);
    return 0;
}