c#编程:接收键盘输入的英文字符串(单词之间用空格隔开),将字符串中出现的单词首字母改成大写后输出

默认分类 未结 1 1479
②ing
②ing 2023-11-27 10:25
相关标签:
1条回答
  • 2023-11-27 11:09

    字符串中,每个单词由空格隔开,空格的个数不限 代码如下: function capitalize(sting) { var words = string.split(" "); for(var i = 0; i < words.length; i++) { words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1); } return words.join(" "); } var string = "ajax cookie event object"; capitalize(string); // "Ajax Cookie Event Object" 注意代码中关键的一句 代码如下: words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1); words[i].charAt(0).toUpperCase()只是取得字符串首字母,然后转换为大写字母,它并不会改变原字符串,所以需要和原字符串中的其他字符连接起来,并将新值赋给原字符串

    using System;using System.Collections.Generic;using System.Linq;using System.Text;namespace ConsoleApplication2{ class Program { static void Main(string[] args) { string [] words = null; StringBuilder strBuff = null; while (true) { try { System.Console.WriteLine("请输入英文字符串!(单词间用空格分隔)"); words = System.Console.ReadLine().Split(new char[] { ' ' }); if (words.Length > 0) { strBuff = new StringBuilder(); strBuff.Append(words[0].ToLower()); for (int i = 1; i < words.Length; i++) { words[i] = words[i].ToLower(); strBuff.AppendFormat("{0}{1}", Char.ToUpper(words[i][0]), words[i].Substring(1)); } System.Console.WriteLine("结果:{0}", strBuff.ToString()); break; } } catch { System.Console.WriteLine("输入不正确!请重新输入"); } } System.Console.Read(); //按回车结束程序 } }}

    0 讨论(0)
提交回复