Convert recursive void to recursive string function in C#

时间:2015-09-01 22:42:33

标签: c# string recursion void

I want to get the results of this code as a string so I can calculate it's length and get the longest string to write it

static void function2(int i, int j, string str)
{
    if (str.Split(' ')[i] == str.Split(' ')[j])
    {
        Console.Write(" {0}", str.Split(' ')[i]);
        i++; j++;
        function2(i, j, str);
    }
}

this is the recursive code that I want to get the result of it(Console.Write(" {0}", str.Split(' ')[i]);) and here is part of the public buddy :

for (m = 0; m < c2 - 1; m++)
{
    i = 0; j = 1;
    while (j < c2)
    {
        function2(i, j, str);
        j++;
    }
    str = str.Remove(0, str.Split(' ')[i].Length + 1);
    c2--;
    Console.WriteLine("");
}

I tried to change the title of the recursive code from static void function2 to static string function2 and add return, but it didn't work.

2 个答案:

答案 0 :(得分:0)

假设您希望保持调用代码不变,只需让function2返回匹配的字符串,您可以执行以下操作:

void Main()
{
    int m; 
    int i; 
    int j; 
    int c2;
    string str = "animals are good and animals are beautiful";

    c2 = str.Split(' ').Length;

    for (m = 0; m < c2 - 1; m++)
    {
       i = 0; j = 1;
       while (j < c2)
       {
           String res = function2(i, j, str);
           // Do what you need to do with the string
           Console.WriteLine(res);
           j++;
       }
       str = str.Remove(0, str.Split(' ')[i].Length + 1);
       c2--;
       Console.WriteLine("");
    }
}

static String function2(int i, int j, string str)
{
    String res = "";

    if (str.Split(' ')[i] == str.Split(' ')[j])
    {
        Console.WriteLine(" {0}", str.Split(' ')[i]);

        // Keep the matching string in a variable
        res = str.Split(' ')[i];

        i++; j++;

        // And add it to the return
        return res + " " + function2(i, j, str);
    }

    // Where it used to be void return an empty string
    return res;
}

答案 1 :(得分:0)

如果你只是想从你的字符串中找到统计数据,而不是真的需要递归,那么这里是一个如何获得你想要的统计数据的例子。请注意,您需要using System.Linq;

var words = str.Split(' ');
var firstWord = words[0];
var hasAnyMore = words.Any(word => word == firstWord);
var longestWord = words.Aggregate((x, y) => x.Length > y.Length ? x : y);
var wordCount = words.Length;