C# ToCharArray() 方法


C# 中的 ToCharArray() 方法用于将此实例中的字符复制到 Unicode 字符数组。

语法

语法如下 -

public char[] ToCharArray ();
public char[] ToCharArray (int begnIndex, int len);

上述 begnIndex 是此实例中子字符串的起始位置。len是此实例中子字符串的长度。

示例

现在让我们看一个示例 -

 在线演示

using System;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "Notebook";
      string str2 = "Ultrabook";
      char[] arr1 = str1.ToCharArray();
      char[] arr2 = str2.ToCharArray();
      Console.WriteLine("String1 = "+str1);
      Console.WriteLine("String1 ToUpperInvariant = "+str1.ToUpperInvariant());
      Console.WriteLine("String1 Substring from index4 = " + str1.Substring(4, 4));
      Console.Write("Character array...String1 =");
      for (int i = 0; i < arr1.Length; i++)
         Console.Write(" " + arr1[i]);
      Console.WriteLine("

String2 = "+str2);       Console.WriteLine("String2 ToUpperInvariant = "+str2.ToLowerInvariant());       Console.WriteLine("String2 Substring from index2 = " + str2.Substring(0, 5));       Console.Write("Character array...String2 =");       for (int i = 0; i < arr2.Length; i++)          Console.Write(" " + arr2[i]);    } }

输出

String1 = Notebook
String1 ToUpperInvariant = NOTEBOOK
String1 Substring from index4 = book
Character array...String1 = N o t e b o o k
String2 = Ultrabook
String2 ToUpperInvariant = ultrabook
String2 Substring from index2 = Ultra
Character array...String2 = U l t r a b o o k

示例

 在线演示

using System;
public class Demo {
   public static void Main(String[] args) {
      string str1 = "Welcome!";
      string str2 = "Thisisit!";
      char[] arr1 = str1.ToCharArray(3,2);
      char[] arr2 = str2.ToCharArray(2,2);
      Console.WriteLine("String1 = "+str1);
      Console.WriteLine("String1 ToUpperInvariant = "+str1.ToUpperInvariant());
      Console.WriteLine("String1 Substring from index4 = " + str1.Substring(4, 4));
      Console.Write("Character array...String1 =");
      for (int i = 0; i < arr1.Length; i++)
         Console.Write(" " + arr1[i]);
      Console.WriteLine("

String2 = "+str2);       Console.WriteLine("String2 ToUpperInvariant = "+str2.ToLowerInvariant());       Console.WriteLine("String2 Substring from index2 = " + str2.Substring(0, 5));       Console.Write("Character array...String2 =");       for (int i = 0; i < arr2.Length; i++)          Console.Write(" " + arr2[i]);    } }

输出

这将产生以下输出 -

String1 = Welcome!
String1 ToUpperInvariant = WELCOME!
String1 Substring from index4 = ome!
Character array...String1 = c o
String2 = Thisisit!
String2 ToUpperInvariant = thisisit!
String2 Substring from index2 = Thisi
Character array...String2 = i s

更新于: 03-12-2019

498 浏览

开启你的 职业生涯

通过完成该课程获得认证

开始
广告