如何使用 C# 逐字(而不是逐字母)反转给定字符串?

csharpserver side programmingprogramming更新于 2025/6/27 20:22:17

创建一个方法 reverse Words,该方法以 char 数组为输入,对每个字符进行反转,直到没有空格为止。最后一步,将整个字符串从长度 0 反转到长度 n-1。在第一步中,字符串"This is my book"将转换为"koob ym si siht"。在第二步结束时,字符串 words 将反转为"book my is This"。

时间复杂度 - O(N)

示例

using System;
namespace ConsoleApplication{
   public class Arrays{
      static void reverse(char[] str, int start, int end){
         char temp;
         while (start <= end){
            temp = str[start];
            str[start] = str[end];
            str[end] = temp;
            start++;
            end--;
         }
      }
      public char[] reverseWords(char[] s){
         int start = 0;
         for (int end = 0; end < s.Length; end++){
            if (s[end] == ' '){
               reverse(s, start, end);
               start = end + 1;
            }
         }
         reverse(s, 0, s.Length - 1);
         return s;
      }
   }
   class Program{
      static void Main(string[] args){
         Arrays a = new Arrays();
         string s = " This is my book ";
         var res = a.reverseWords(s.ToCharArray());
         Console.WriteLine(new String(res));
         Console.ReadLine();
      }
   }
}

输出

book my is This

相关文章