C#方法返回一个字符串? [英] c# Method to return a string?

查看:1187
本文介绍了C#方法返回一个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

该方法应该具有循环并返回字符串.我怎么做?这是我到目前为止所拥有的.我是C#的新手.

This method is supposed to have a loop and return a string. How do I do that? This what I have so far. I'm new to C#.

public string BLoop()
{
    for (int i = 99; i > 0; i--)
    {
        Console.WriteLine(string.Format("{0} bottles of beer on the wall, {0}   bottles of beer.", i));
        Console.WriteLine(string.Format("Take one down, pass it around, {1} bottles of beer on the wall.", i, i - 1));
        Console.WriteLine();
    }
}

++我尝试了您建议的所有操作,但是我认为我应该改写应该返回由主程序打印的字符串的方法.

++ I tried all the thing you suggested but I think I should rephrase the method is supposed to return a string that is printed by the main.

推荐答案

我假设您需要返回循环中构造的字符串(而不是其他答案中的任意字符串).您需要构建一个字符串,而不是只写出字符串,然后返回该字符串:

I'm assuming you need to return the string constructed in your loop (and not just some arbitrary string as in the other answers). You need to build a string instead of just writing the strings out, then return that string:

public string BLoop()
{
    var builder = new StringBuilder();
    for (int i = 99; i > 0; i--)
    {
        builder.AppendLine(string.Format("{0} bottles of beer on the wall, {0} bottles of beer.", i));
        builder.AppendLine(string.Format("Take one down, pass it around, {0} bottles of beer on the wall.", i-1));
    }

    return builder.ToString();
}

请注意,我还修改了循环的第二行,以消除冗余的String.Format参数.

Note that I've also amended the second line of your loop to eliminate the redundant String.Format parameter.

这篇关于C#方法返回一个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆