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

王林
Release: 2023-09-12 19:25:02
forward
1419 people have browsed it

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

Assume the following is your string -

String str = "Welcome to our website!";
Copy after login

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

char []ch = str.ToCharArray();
Copy after login

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;);
}
Copy after login

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));
   }
}
Copy after login

Output

Welcome To Our Website!
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template