Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 在foreach循环中浓缩字符串时出错_C#_.net_String - Fatal编程技术网

C# 在foreach循环中浓缩字符串时出错

C# 在foreach循环中浓缩字符串时出错,c#,.net,string,C#,.net,String,我想在代码字中显示公司名称,如Dell Computers=DC,但在连接字符串时出错 string str = txtCompanyname.Text.Trim(); string[] output = str.Split(' '); foreach (string s in output) { // Console.Write(s[0] + " ");

我想在代码字中显示公司名称,如Dell Computers=DC,但在连接字符串时出错

         string str = txtCompanyname.Text.Trim();

            string[] output = str.Split(' ');
            foreach (string s in output)
            {
               // Console.Write(s[0] + " ");
                Response.Write(s[0]);
                string newid += s[0].ToString();//getting error here

            }
在foreach循环外部定义NewID。不能同时定义和分配变量

 string str = txtCompanyname.Text.Trim();
 string[] output = str.Split(' ');
 string newid= string.empty;
 foreach (string s in output)
  {
     // Console.Write(s[0] + " ");
        Response.Write(s[0]);
        newid += s[0].ToString();//getting error here

  }

您可以使用linq来完成

只需拆分全名并选择每个部分的第一个字符

string str = "Dell Computers";
var abbr = new string(str.Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries)
    .Select(x => char.ToUpper(x[0]))
    .ToArray());

可以使用LINQ执行以下操作:

public string FirstLetters(string s)
{
    return String.Join("", s.Trim().Split(' ').Select(w => w.Substring(0, 1).ToUpper()));
}

var result = FirstLetter(txtCompanyname.Text);
此代码执行以下操作:

修剪你的绳子 用空格将字符串拆分为一组单独的单词 通过从每个单词中提取第一个大写字母生成集合 将字母集合合并为字符串
public string FirstLetters(string s)
{
    return String.Join("", s.Trim().Split(' ').Select(w => w.Substring(0, 1).ToUpper()));
}

var result = FirstLetter(txtCompanyname.Text);