='a'&&ch[i]<='z'){ //ConvertintoUpper-ca"/> ='a'&&ch[i]<='z'){ //ConvertintoUpper-ca">

Home >Backend Development >C#.Net Tutorial >C# program to convert first character in sentence to uppercase

C# program to convert first character in sentence to uppercase

王林
王林forward
2023-09-12 19:25:021399browse

C# 程序将句子中的第一个字符转换为大写

Assume the following is your string -

String str = "Welcome to our website!";

Use the ToCharArray() method to create a char array of the string contained above:

char []ch = str.ToCharArray();

Convert first character to uppercase -

if (ch[i] >= &#39;a&#39; &amp;&amp; ch[i] <= &#39;z&#39;) {
   // Convert into Upper-case
   ch[i] = (char)(ch[i] - &#39;a&#39; + &#39;A&#39;);
}

Example

You can try running the following code to convert the first character in a sentence to uppercase.

Live Demo

using System;
class Demo {
   static String MyApplication(String str) {
      char []val = str.ToCharArray();
      for (int i = 0; i < str.Length; i++) {
         if (i == 0 && val[i] != ' ' ||
            val[i] != ' ' && val[i - 1] == ' ') {
               if (val[i] >= 'a' && val[i] <= 'z') {
                  val[i] = (char)(val[i] - 'a' + 'A');
               }
            } else if (val[i] >= 'A' && val[i] <= 'Z')
               val[i] = (char)(val[i] + 'a' - 'A');
      }
      String s = new String(val);
      return s;
   }
   public static void Main() {
      String str = "Welcome to our website!";
      Console.Write(MyApplication(str));
   }
}

Output

Welcome To Our Website!

The above is the detailed content of C# program to convert first character in sentence to uppercase. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete