C#如何实现句子中每个单词首尾字符互换并全部转为小写
C# 单词首尾字符互换+全小写功能实现方案
你当前编写的代码仅完成了字符串全转小写的逻辑,尚未实现单词首尾字符交换的功能,按需求调整的逻辑如下:
调整思路
- 处理单字符单词特殊情况:如果单词长度为1,无需交换首尾,直接转小写即可
- 长度≥2的单词:拆分出首字符、中间字符段、尾字符,按「尾字符 + 中间字符段 + 首字符」的规则重组单词
- 重组后的单词直接调用
ToLower()统一转小写,无需逐个字符判断是否为大写,代码更简洁
调整后完整代码
using System; namespace ConsoleApp11 { class Program { static void Main(string[] args) { string text = "Hello world"; string[] words = text.Split(" "); string output = ""; for(int i = 0; i < words.Length; i++) { string currentWord = words[i]; if (currentWord.Length == 1) { output += currentWord.ToLower() + " "; continue; } // 交换首尾字符 char firstChar = currentWord[0]; char lastChar = currentWord[currentWord.Length - 1]; string middlePart = currentWord.Substring(1, currentWord.Length - 2); string processedWord = lastChar + middlePart + firstChar; // 统一转小写后拼接 output += processedWord.ToLower() + " "; } // 去除末尾多余的空格 output = output.TrimEnd(); Console.WriteLine(output); } } }
运行验证
输入字符串Hello world时,运行后输出结果为:oellh dorlw,符合需求要求。
内容的提问来源于stack exchange,提问作者Yaroslav Yatsyk
相关产品推荐
相关产品推荐

