代码之家  ›  专栏  ›  技术社区  ›  Klang

我怎么做我自己的绳子。Split()和数组。Reverse()一个用户定义函数中的内置函数,用于反转给定字符串?

  •  0
  • Klang  · 技术社区  · 2 年前

    我试过这个:

    using System;
    using System.Collections;
    using System.Collections.Generic;
    
    public class HelloWorld
    {
        public static string reverseWords(string str){
            ArrayList strArr = new ArrayList();
            int start = 0;
            string revStr = "";
            for(int i = 0; i < str.Length; i++){ 
                if(str[i] == ' '){               // if there's a space,
                    while(start <= str[i - 1]){  // loop thru the iterated values before space
                        strArr.Add(str[start]);  // add them to the ArrayList
                        start++;                 // increment `start` until all iterated values are-
                    }                            // stored and also for the next word to loop thru
                }
            }
            for(int j = strArr.Count - 1; j >= 0;  j--){
                revStr += strArr[j] + " ";             // keep appending ArrayList values to the-
            }                                          // string from the last to the first value
            return revStr;
        }
        
        public static void Main(string[] args)
        {
           Console.WriteLine(reverseWords("Our favorite color is Pink"));
           //Expected output : Pink is color favorite Our 
        }
    }
    

    它给出了一个错误:

    System.IndexOutOfRangeException: Index was outside the bounds of the array.
    

    请帮助我理解为什么这不起作用。此外,如果有更好的方法手动执行ReverseWord函数(根本不使用任何内置函数)。

    如果这是一个愚蠢的问题,我很抱歉。欢迎任何建设性的批评。谢谢

    2 回复  |  直到 2 年前
        1
  •  2
  •   Abdelkrim    2 年前

    这里是您的代码的一个稍加改进的版本,它实际上适用于您愿意做的事情。

    using System;
    using System.Collections;
    
    public class HelloWorld
    {
        public static string reverseWords(string str){
            ArrayList strArr = new ArrayList();
            string currentWordString = string.Empty; 
            string revStr = string.Empty;
            for(int i = 0; i < str.Length; i++){ 
                if(str[i] == ' '){               // if there's a space,
                    strArr.Add(currentWordString); // add the accumulated word to the array
                    currentWordString = string.Empty; // reset accumulator to be used in next iteration
                }else {
                    currentWordString += str[i]; // accumulate the word
                }
            }
            
            strArr.Add(currentWordString); // add last word to the array
            
            
            for(int j = strArr.Count - 1; j >= 0;  j--){
                revStr += strArr[j] + " ";             // keep appending ArrayList values to the-
            }                                          // string from the last to the first value
            return revStr;
        }
        
        public static void Main(string[] args)
        {
           Console.WriteLine(reverseWords("Our favorite color is Pink"));
           //Expected output : Pink is color favorite Our 
        }
    }
    

    我会让你做剩下的。比如去掉句子末尾的trailing空格。添加空格以外的分隔符(例如逗号、分号…)

        2
  •  1
  •   H-a-Neo    2 年前

    试试这个

     "Our favorite color is Pink".Split('\u0020').Reverse().ToList().ForEach(x =>
      {
          Console.WriteLine(x);
      });
    
        3
  •  1
  •   Koref Koref    2 年前

    这会有帮助

        public static string ReverseCharacters(string str)
        {
            if(str == null)
            {
                throw new ArgumentNullException(nameof(str));
            }
    
            int lastIndex = str.Length - 1;
            char[] chars = new char[str.Length];
    
            char temp;
            for(int i = 0; i < str.Length/2+1; i++)
            {
                // Swap. You could refactor this to its own method if needed
                temp = str[i];
                chars[i] = str[lastIndex - i];
                chars[lastIndex - i] = temp;
            }
    
            return new string(chars);
        }
    
        public static string ReverseWords(string str)
        {
            if (str == null)
            {
                throw new ArgumentNullException(nameof(str));
            }
    
            if (string.IsNullOrWhiteSpace(str))
            {
                return str;
            }
    
            string space = " ";
            StringBuilder reversed = new StringBuilder();
            // reverse every characters
            var reversedCharacters = ReverseCharacters(str);
            // split words (space being word separator here)
            var reversedWords = reversedCharacters.Split(space);
            // for every revered word characters, reverse it back one more time and append.
    
            foreach(var reversedWord in reversedWords)
            {
                reversed.Append(ReverseCharacters(reversedWord)).Append(space);
            }
    
            // remove last extra space
            reversed = reversed.Remove(reversed.Length - 1, 1);
    
            return reversed.ToString();
        }
    

    以下是测试结果:

    enter image description here