如何在字符串中添加逗号? [英] How to add commas to a string?

查看:865
本文介绍了如何在字符串中添加逗号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想输出我的字符串如下:



字,字,字



目前,我无法用逗号分隔字符串。请告知我可能出错的地方 - 谢谢。



我尝试了什么:



 SqlDataReader reader = command.ExecuteReader(); 
while (reader.Read())
{


string content =(reader.GetString( 0 ));

result =结果+ 字符串 .Join( ,content);


// 返回结果;
}
}
返回结果;
}

解决方案

参见String.Join Method(System) [ ^ ]。


String.Join需要多个第二个参数的某种形式的字符串,所以你需要将所有结果读入某种字符串列表然后将其传递给String.Join



 List< string> contentResults =  new  List< string>(); 

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
contentResults.Add(reader.GetString( 0 ));
}

result = string .Join( ,contentResult);
< / string > < / string >


除了上述2解决方案之外,还有另外一种添加逗号的方法

 StringBuilder result =  new  StringBuilder(); 
while (reader.Read())
{
string content =(reader.GetString( 0 ));
result.Append(content + ); ;
}
return result.ToString()。TrimEnd(' );


I would like to output my string as following:

Word, word, word

Currently, I am unable split the string up with the commas. Please advise as to where I may be going wrong – thank you.

What I have tried:

SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {


                        string content = (reader.GetString(0));

                        result = result + string.Join(",", content);


                        //return result;
                    }
                }
                return result;
            }

解决方案

See String.Join Method (System)[^].


String.Join takes multiple strings in some form for the second argument, so you need to read all your results into a string list of some sort and then pass that in once to String.Join

List<string> contentResults = new List<string>();

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
    contentResults.Add(reader.GetString(0));
}

result = string.Join(", ", contentResult);
</string></string>


In addition to above 2 solution, here is the another way of adding comma's

StringBuilder result = new StringBuilder();
 while (reader.Read())
        {
            string content = (reader.GetString(0));
            result.Append(content + ","); ;
        }
        return result.ToString().TrimEnd(',');


这篇关于如何在字符串中添加逗号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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