如何在一个用户定义的功能中制作自己的字符串split()和array.revers()内置函数以逆转给定的字符串?
我已经尝试过:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是您的代码的一些改进版本,实际上适合您愿意做的事情。
我会让你做剩下的。就像在句子结尾处删除训练空间一样。添加除空间以外的其他移动器(例如逗号,半殖民地...)
Here is a little improved version of your code that actually works for what you are willing to do.
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...)
尝试一下
Try this
将有所帮助
测试结果
:
This will help
Here is the test result: