简体   繁体   English

如何在一个用户定义的函数中创建自己的 String.Split() 和 Array.Reverse() 内置函数来反转给定的字符串?

[英]How do I make my own String.Split() and Array.Reverse() built-in functions in one user-defined function to reverse a given string?

I have tried this:我试过这个:

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 
    }
}

And it's giving this error:它给出了这个错误:

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

Please help me understand why this is not working.请帮助我理解为什么这不起作用。 And also, if there's better way to do this ReverseWord function manually(not using any built-in functions at all).而且,如果有更好的方法来手动执行此 ReverseWord 函数(根本不使用任何内置函数)。

I'm sorry if this is such a noob question.如果这是一个菜鸟问题,我很抱歉。 Any constructive criticism is appreciated.任何建设性的批评都是值得赞赏的。 Thanks!谢谢!

Here is a little improved version of your code that actually works for what you are willing to do.这是您的代码的一个稍微改进的版本,它实际上适用于您愿意做的事情。

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 
    }
}

I'll let you do the remaining.我会让你做剩下的。 Like removing the trainling space at the end of the sentence.就像删除句子末尾的训练空间一样。 add seperators other than space (eg comma, semicolons...)添加空格以外的分隔符(例如逗号、分号...)

["

Try this<\/i>尝试这个<\/b><\/p>

 "Our favorite color is Pink".Split('\u0020').Reverse().ToList().ForEach(x =>
  {
      Console.WriteLine(x);
  });

This will help这将有助于

    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();
    }

Here is the test result:这是测试结果:

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM