C语言 反转句子中单词的顺序

这篇博客探讨了如何使用C语言将句子中的单词顺序反转,例如将'I am your friend'转换为'friend your am I',涉及字符串处理和内存操作技巧。
摘要由CSDN通过智能技术生成

将"I am your friend"转为"friend your am I"。



#include <iostream>
#include <stdlib.h> 

void reverse(char* pBegin, char* pEnd)//反转任意的字符串
{
   	if(pBegin == NULL || pEnd == NULL)
    {
        return;
    }
    
	while(pBegin <  pEnd)
    {
		
		char temp=*pBegin;
		*pBegin=*pEnd;
		*pEnd=temp;
		pBegin++;
        pEnd--;
	
	}

	return;
}
void reverse_sentence(char* begin)
{
    if(begin == NULL)
    {
        return;
    }
	
	char* end=begin;

    while(*end != '\0')
    {
        end++;
    }
    end--;
    reverse(begin,end);//先反转整句话

    end=begin;

    /*开始逐个反转单词*/
    while(*begin != '\0')
    {
        if(*begin == ' ')//跳过空格
        {
            begin++,end++;
            continue;
        }
        else if(*end == ' ' || *end == '\0')
        {
要使用栈实现字符串所有单词顺序反转,可以按照以下步骤进行操作: 1. 创建一个字符栈。 2. 遍历字符串的每个字符: - 如果当前字符不是空格,则将其入栈。 - 如果当前字符是空格: - 反向输出栈的字符,实现单词顺序反转。 - 打印空格。 3. 最后,如果栈还有字符,说明最后一个单词没有被打印出来,将栈的字符反向输出。 以下是使用C语言实现的示例代码: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> // 定义字符栈结构 struct Stack { char* data; int top; int maxSize; }; // 初始化栈 void initStack(struct Stack* stack, int maxSize) { stack->data = (char*)malloc(maxSize * sizeof(char)); stack->top = -1; stack->maxSize = maxSize; } // 判断栈是否为空 int isStackEmpty(struct Stack* stack) { return stack->top == -1; } // 判断栈是否已满 int isStackFull(struct Stack* stack) { return stack->top == stack->maxSize - 1; } // 入栈 void push(struct Stack* stack, char c) { if (isStackFull(stack)) { return; } stack->data[++stack->top] = c; } // 出栈 char pop(struct Stack* stack) { if (isStackEmpty(stack)) { return '\0'; } return stack->data[stack->top--]; } // 字符串所有单词顺序反转 void reverseWordsOrder(char* str) { int len = strlen(str); struct Stack stack; initStack(&stack, len); for (int i = 0; i < len; i++) { if (str[i] != ' ') { push(&stack, str[i]); } else { while (!isStackEmpty(&stack)) { printf("%c", pop(&stack)); } printf(" "); } } while (!isStackEmpty(&stack)) { printf("%c", pop(&stack)); } } int main() { char str[] = "Hello World! This is a test."; printf("原始字符串:%s\n", str); printf("单词顺序反转后的字符串:"); reverseWordsOrder(str); return 0; } ``` 以上是一个使用栈实现字符串所有单词顺序反转的示例代码。它会按照单词顺序将字符串的每个单词反转输出。您可以根据自己的需求进行修改和使用。希望对您有帮助!如有任何疑问,请随时追问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值