注册账号 登录
用友之家-用友软件论坛 返回首页

wozengcong的个人空间 https://www.oyonyou.com/?242966 [收藏] [复制] [分享] [RSS]

日志

delphi中的copy,delete,pos和leftstr,RightStr的用法

已有 4606 次阅读2013-5-2 20:54 |个人分类:Delphi7| 字符串

举个例子:str := “123456”;str1 := Copy(Str,2,3);结果就是 str1 等于 234。Copy有3个参数,第一个是你要处理的字符串,第二个是你要截取的开始位置,第3个是截取位数。当你的第3个参数大于字符长度,那么效果就是取 开始位置 后的所有字符。str1 := Copy(Str,2,10); 结果就是str1 等于 23456。

leftstr和pos

假设字符串是 S := ’Delphi is the BEST’, 那么
LeftStr(S, 5) := ’Delph’ //即S前5位字符
MidStr(S, 6, 7) := ’i-is-th’// 即s的第六位开始后面7个字符(-:=空格)
RightStr(S, 6) := ’e-BEST’//即S后面的字符(-:=空格)

取出子串在父串中第一次出现的位置
例如
pos('b','abcd');
返回结果是2//pos就是显示B在整个字符中排第几位


delete

列子:

var
S: string;
begin
S := '12345';
Delete(S, 2, 2);
ShowMessage(S);//显示 145 即删除 23.即是删掉S的第二位开始的2个字符。
end;

这几个函数都包含在StrUtils中,所以需要uses StrUtils; 
假设字符串是 Dstr := ’Delphi is the BEST’, 那么 
LeftStr(Dstr, 5) := ’Delph’ 
MidStr(Dstr, 6, 7) := ’i is th’ 
RightStr(Dstr, 6) := ’e BEST’ 

~~~~~~~~~~~~~~~~~~~~~~~~~ 
function RightStr 
    (Const Str: String; Size: Word): String; 
begin 
  if Size > Length(Str) then Size := Length(Str) ; 
  RightStr := Copy(Str, Length(Str)-Size+1, Size) 
end; 
function MidStr 
    (Const Str: String; From, Size: Word): String; 
begin 
  MidStr := Copy(Str, From, Size) 
end; 
function LeftStr 
    (Const Str: String; Size: Word): String; 
begin 
  LeftStr := Copy(Str, 1, Size) 
end; 

这几个函数经常结合Pos, Length, Copy使用


拆分字符串的函数  [2005-12-13]
  
delphi中没有提供此类函数,从大富翁找了一个

function split(src,dec : string):TStringList;
var
  i : integer;
  str : string;
begin
  result := TStringList.Create;
  repeat
    i := pos(dec,src);
    str := copy(src,1,i-1);
    if (str='') and (i>0) then
    begin
      delete(src,1,length(dec));
      continue;
    end;
    if i>0 then
    begin
      result.Add(str);
      delete(src,1,i+length(dec)-1);
    end;
  until i<=0;
  if src<>'' then
    result.Add(src);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  ss : TStringList;
  str,dec : string;
begin
  str := '1111||2222||||3333|||4444||';
  dec := '||';
  ss := split(str,dec);
  memo1.Lines.AddStrings(ss);
  ss.Free;
end;

路过

雷人

握手

鲜花

鸡蛋

评论 (0 个评论)

facelist

您需要登录后才可以评论 登录 | 注册账号

QQ|站长微信|Archiver|手机版|小黑屋|用友之家 ( 蜀ICP备07505338号|51072502110008 )

GMT+8, 2024-5-15 08:47 , Processed in 0.016894 second(s), 10 queries , Gzip On, Redis On.

Powered by Discuz! X3.5

© 2001-2024 Discuz! Team.

返回顶部