单词倒序

本文介绍了一个使用C语言实现的单词倒序输出程序。该程序通过读取包含空格的字符串,将其拆分为单词,并将单词顺序反转后输出。涉及的主要技术包括字符串处理和数组操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

2019/3/11就胡凡大佬的算法笔记学习开始。距20号参加ICDM复试还有9天

#include <stdio.h>
#include <stdlib.h>
#include <string.h> 
/*
单词倒序输出 
*/
int main(int argc, char *argv[]) {
	char ans[100][100];
	char str[100];
	gets(str);	//包含空格输入字符串 
	int len=strlen(str);
	int i;
	int r=0,h=0;
	for(i=0;i<len;++i){
		if(str[i]!=' '){	//空格符中间就是要空格 
			ans[r][h++]=str[i];//用二维数组表示单词 
		}
		else{
			r++;
			h=0;
		}
	}
	for(i=r;i>=0;--i){
	printf("%s",ans[i]);//输出时单词只需要输出一维数组,格式时%s 
	if(i>0)
	printf(" ");
	}
	return 0;
}

 

### 实现Python单词字符串倒序的方法 在Python中,可以通过多种方式实现单词级别的字符串倒序功能。以下是几种常见的方法及其解释。 #### 方法一:使用 `split` 和 `join` 通过先将字符串按空格分割成列表,再反转该列表并重新拼接为字符串的方式实现单词倒序[^1]。 ```python def reverse_words(sentence): words = sentence.split() # 将句子拆分为单词列表 reversed_words = words[::-1] # 使用切片操作反转列表 result = " ".join(reversed_words) # 将反转后的单词列表重新连接为字符串 return result sentence = "I am a student" reversed_sentence = reverse_words(sentence) print(reversed_sentence) # 输出: student a am I ``` --- #### 方法二:手动遍历与累加 这种方法通过对原始字符串进行逐字符处理,在遇到空格时记录当前单词,并将其加入到结果列表的开头位置[^2]。 ```python def reverse_words_manual(sentence): word_list = [] current_word = "" for char in sentence: if char != ' ': # 如果不是空格,则累积当前单词 current_word += char else: # 遇到空格表示一个单词结束 if current_word: # 确保当前单词非空 word_list.insert(0, current_word) # 插入到列表头部 current_word = "" # 清空当前单词 # 处理最后一个单词 if current_word: word_list.insert(0, current_word) return " ".join(word_list) sentence = "We are happy people" reversed_sentence = reverse_words_manual(sentence) print(reversed_sentence) # 输出: people happy are We ``` --- #### 方法三:正则表达式匹配 利用正则表达式提取所有单词,并对其进行逆向排列[^3]。 ```python import re def reverse_words_regex(sentence): words = re.findall(r'\b\w+\b', sentence) # 提取所有单词 reversed_words = words[::-1] # 反转单词顺序 return " ".join(reversed_words) sentence = "This is an example string." reversed_sentence = reverse_words_regex(sentence) print(reversed_sentence) # 输出: string. example an is This ``` --- #### 注意事项 - 上述三种方法均假设输入字符串由标准英文单词组成,且单词间仅存在单个空格分隔。 - 若需考虑特殊字符(如连字符 `-` 或下划线 `_`),可适当调整逻辑以满足具体需求[^4]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值