如何用 Python C PHP 实现字符反转? 字符串反序输出?
字符反转一. python1.字符串切片2.reverse3.reduce4.递归函数5. 栈6.for循环二.C语言1.2.给定一个字符串,然后将其翻转,逆序输出一. python1.字符串切片s = "123ABC"s = s[::-1]print(s)2.reverses="123ABC"print("".join(reversed(s)))s = "123ABC"l = list(s)l.
·
给定一个字符串,然后将其翻转,逆序输出
一. 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;
}
三、PHP
<?php
echo strrev("Hello world!"); // 输出 !dlrow olleH
?>
更多推荐
已为社区贡献4条内容
所有评论(0)