System.Copy - 从字符串或数组中复制

function Copy(
  S: String;      {字符串或动态数组}
  Index: Integer; {起始位置}
  Count: Integer  {Copy 个数}
): String;        {如果参数 S 是动态数组, 这里也应该返回动态数组}


//从字符串中提取
var
  ss,s: string;
begin
  ss := 'CodeGear Delphi 2007';
  s := Copy(ss,5,4);
  ShowMessage(s);   {Gear}
end;



//从静态字符数组中截取字符串
var
  arr: array[0..25] of Char;
  s: string;
  i: Integer;
begin
  {给 arr 装入 26 个大写字母}
  for i := Low(arr) to High(arr) do
    arr[i] := Chr(i+65);
    
  {提取}
  s := Copy(arr, 1, 3);
  ShowMessage(s);       {ABC}
end;



//从动态数组到动态数组
var 
  arr1,arr2 : array of Integer;
  i: Integer;
begin
  {设定数组大小}
  SetLength(arr1, 10);

  {给数组赋值}
  for i := Low(arr1) to High(arr1) do
    arr1[i] := i;

  {执行 Copy; 注意: 之前没有给 arr2 设置大小, 就是设置了, 在这里也会被重置!}
  arr2 := Copy(arr1, 0, 3);

  for i in arr2 do
    ShowMessage(IntToStr(i)); {会分别显示: 0、1、2}
end;




//关于起始位置(仅对字符串, 动态数组另当别论)
const
  ss = 'ABCDEFG';
var
  s: string;
begin
  s := Copy(ss, 1, 3);
  ShowMessage(s);        {ABC}
  s := Copy(ss, 0, 3);
  ShowMessage(s);        {ABC}
  s := Copy(ss, -1, 3);
  ShowMessage(s);        {ABC}
  s := Copy(ss, -100, 3);
  ShowMessage(s);        {ABC}
end;



//关于 Copy 个数
const
  ss = 'ABCDEFG';
var
  s: string;
begin
  s := Copy(ss, 2, 6);
  ShowMessage(s);               {BCDEFG}
  s := Copy(ss, 2, Length(ss));
  ShowMessage(s);               {BCDEFG}
  s := Copy(ss, 2, MaxInt);
  ShowMessage(s);               {BCDEFG}
end;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,我明白了。下面是我的回答: 1)在C#中,可以使用System.IO命名空间中的File类来创建文件和写入文件内容。代码如下: ``` string filePath = @"D:\Experiment.txt"; string content = "这是我写入的第一个文件"; File.WriteAllText(filePath, content); ``` 2)读取文件内容可以使用File类中的ReadAllLines方法,该方法可以将文件按行读取并返回一个字符串数组。然后可以使用File类中的WriteAllLines方法将字符串数组中的内容写入到另一个文件中。具体代码如下: ``` string readPath = @"D:\Experiment.txt"; string writePath = @"D:\output.txt"; string[] lines = File.ReadAllLines(readPath); File.WriteAllLines(writePath, lines); ``` 3)为了提高效率,可以使用FileStream类来进行文件读写操作。具体代码如下: ``` string filePath = @"D:\Experiment.txt"; string content = "这是我写入的第一个文件"; byte[] bytes = Encoding.UTF8.GetBytes(content); using (FileStream stream = new FileStream(filePath, FileMode.Create)) { stream.Write(bytes, 0, bytes.Length); } string readPath = @"D:\Experiment.txt"; string writePath = @"D:\output.txt"; using (FileStream readStream = new FileStream(readPath, FileMode.Open)) using (FileStream writeStream = new FileStream(writePath, FileMode.Create)) { readStream.CopyTo(writeStream); } ``` 使用FileStream类进行文件读写操作可以避免文件一次性读取或写入过大而导致内存溢出的问题,提高效率同时也更加稳定可靠。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值