ToCharArray()
方法将字符串中的字符复制到字符数组中。
示例
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
char[] result;
// copies str to result
result = str.ToCharArray();
// prints result
for (int i = 0; i < result.Length; i++) {
Console.Write(result[i] + ", ");
}
Console.ReadLine();
}
}
}
// Output: I, c, e, c, r, e, a, m,
ToCharArray() 语法
字符串 ToCharArray()
方法的语法是:
ToCharArray(int startIndex, int length)
此处,ToCharArray()
是 String
类的一个方法。
ToCharArray() 参数
ToCharArray()
方法接受以下参数:
- startIndex - 字符串中子字符串的起始位置
- length - 字符串中子字符串的长度
ToCharArray() 返回值
- 返回一个
char
数组。
示例 1:C# String ToCharArray()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Chocolate";
char[] result;
// copies str to result
result = str.ToCharArray();
// prints result
for (int i = 0; i < result.Length; i++) {
Console.WriteLine(result[i]);
}
Console.ReadLine();
}
}
}
输出
C h o c o l a t e
示例 2:带参数的 C# String ToCharArray()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
char[] result;
// copies 4 chars from index 3 of str
result = str.ToCharArray(3, 4);
// prints result
for (int i = 0; i < result.Length; i++) {
Console.WriteLine(result[i]);
}
Console.ReadLine();
}
}
}
输出
c r e a
请注意以下代码,
str.ToCharArray(3, 4)
这里,
- 3 - 要从中复制字符的起始索引
- 4 - 要复制的字符串长度