C# String ToCharArray() 字符串转字符数组方法
ToCharArray()
方法将字符串中的字符复制到字符数组中。
示例
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
char[] result;
// 将 str 复制到 result
result = str.ToCharArray();
// 打印 result
for (int i = 0; i < result.Length; i++) {
Console.Write(result[i] + ", ");
}
Console.ReadLine();
}
}
}
// 输出: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# 字符串 ToCharArray()
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Chocolate";
char[] result;
// 将 str 复制到 result
result = str.ToCharArray();
// 打印 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# 字符串 ToCharArray() 使用参数
using System;
namespace CsharpString {
class Test {
public static void Main(string [] args) {
string str = "Icecream";
char[] result;
// 从 str 的索引 3 复制 4 个字符
result = str.ToCharArray(3, 4);
// 打印 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 - 要复制的字符串长度