将c#中的递归void函数转换为递归string函数

本文关键字:函数 递归 转换 string void | 更新日期: 2023-09-27 18:10:49

我想把这段代码的结果作为一个字符串,这样我就可以计算它的长度并得到最长的字符串来写它

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

这是递归代码,我想得到它的结果(Console.Write(" {0}", str.Split(' ')[i]);)这里是公共伙伴的一部分:

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

我试图将递归代码的标题从static void function2更改为static string function2并添加返回,但它没有工作

将c#中的递归void函数转换为递归string函数

假设您想保持调用代码原样,只是让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;
}

如果您只是从字符串的单词中查找统计信息,并且不真正需要递归,那么这里有一个如何获得您想要的统计信息的示例。注意,您需要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;