C语言中输入一个英语句子将它翻转后输出

Python012

C语言中输入一个英语句子将它翻转后输出,第1张

完成!输入句子,回车换行。之后Ctrl+Z结束输入,支持句子和段落反转输出。size是最大字符数,我设的为30,你可以自己修改,也可以用realloc设成动态数组。有什么不懂得地方可以接着问我。

#include <stdio.h>

#include <malloc.h>

#include<string.h>

#define size 30

int main()

{

char *a

int b

a=(char*)malloc(size*sizeof(char))

scanf("%[^/n]",a)

b=strlen(a)

for(b>0b--)

printf("%c",a[b-1])

printf("\n")

return 0

}

自己写的一个,用C标准库字符串函数实现的,指针用不好很容易出错。

主要思路:将整个句子以空格“ ”分割成多个字符串,保存在临时数组str_tmp[MAXLEN][20]中将临时数组反序写入到str_reverse[MAXLEN]中,输出就可以了。

源程序:

#include <stdio.h>

#include <string.h>

#define MAXLEN 80

void main()

{

//char str[MAXLEN] = "what is your name"

char str[MAXLEN] = {0}

char str_tmp[MAXLEN][20] = {0}

char str_reverse[MAXLEN] = {0}

char *p,*delim = " "

int i = 0,n

printf("please input :")               //长度不要超过MAXLEN=80,可以修改宏;

scanf("%[^\n]",str)                       //允许输入空格,遇回车才结束输入;

p = strtok(str,delim)

while(p != NULL)

{

strcpy(str_tmp[i],p)                    //分割的字符串保存到临时数组;

p = strtok(NULL,delim)

i++

}

for(n = i-1n >= 0n--)

{

strcat(str_reverse,str_tmp[n])       //将临时数组从后往前的字符串追加到反序数组中;

strcat(str_reverse," ")

}

printf("%s\n",str_reverse)

}

运行结果截图:

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#include<ctype.h>

#define OK 1

#define M 5

//建单词节点

struct Node{

char *data

Node *next

}

char f

//插入函数

void Insert(Node* &S,char e[])

{

Node *p

p=(Node *)malloc(sizeof(Node))

p->data = (char *)malloc(strlen(e)+1)

p->next = NULL

    strcpy(p->data,e)

p->next = S

S  = p

}

void Creat(Node* &S)

{

int i = 0,k = 0,j,flag = 1,insert

char s[20]

char a[2000] = {0}

    printf("\n输入正文:  ")

fflush(stdin) 

gets(a)

    printf("\n原文为:  ")

while(a[i] != NULL)

{

insert = 0

memset(s, 0, 20)

j = 0

// 跳过单词前面的前导字符

while(flag&&!isalpha(a[i])||a[i]==39)//39为'的ASCII码

{

i++

if(a[i]==NULL)

flag = 0

}

// 当前单词尚未结束,则一直循环

while(flag&&isalpha(a[i])||a[i]==39)

{

insert = 1

s[j]=tolower(a[i])

i++

j++

}

//单词插入

if(insert)

{

s[i] = '\0'

k++

printf("%s\t", s)

if(k%5 == 0)

printf("\n")

Insert(S,s)

j++

}

}

if(!isalpha(a[i-1]))

f = a[i-1]

else

f=' '

}

//输出正文    

void Print(Node* &T)

{

    if(NULL!=T)

    {

printf("%s ",T->data)

Print(T->next)

}

else

return

}

int main()

{

    Node *S=NULL

Creat(S)

printf("\n倒置为:")

Print(S)

printf("%c",f)

printf("\n")

    return 0

}

2013 5 25 8:16

耗时14min

1L