如何在一个用户定义的功能中制作自己的字符串split()和array.revers()内置函数以逆转给定的字符串?

发布于 2025-02-06 15:54:52 字数 1465 浏览 2 评论 0原文

我已经尝试过:

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.

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

很抱歉,如果这是一个菜鸟问题。任何建设性的批评都将受到赞赏。谢谢!

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).

I'm sorry if this is such a noob question. Any constructive criticism is appreciated. Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

苏别ゝ 2025-02-13 15:54:52

这是您的代码的一些改进版本,实际上适合您愿意做的事情。

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

我会让你做剩下的。就像在句子结尾处删除训练空间一样。添加除空间以外的其他移动器(例如逗号,半殖民地...)

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 (e.g comma, semicolons...)

几味少女 2025-02-13 15:54:52

尝试一下

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

Try this

 "Our favorite color is Pink".Split('\u0020').Reverse().ToList().ForEach(x =>
  {
      Console.WriteLine(x);
  });
网白 2025-02-13 15:54:52

将有所帮助

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

测试结果

”在此处输入图像描述

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:

enter image description here

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文