欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Delphi中常用字符串处理函数

程序员文章站 2022-03-10 12:41:12
转发于:https://blog.csdn.net/mrwlw/article/details/78238434 ......
1.copy(str,pos,num) 从str字符串的pos处开始,截取num个字符的串返回.
假设str为'abcdef',copy(str,3,2)='cd',copy(str,4,10)='def' 
2.concat(str1,str2{,strn}) 把各自变量连接起来,返回连接后的字符串(长度不能超过255) 
3.length(str)       返回str的字符个数,即其长度. 
4.pos(obj,target)   在target字符串中找出第一个出现obj的第一个字符位置,如果找不到,返回0. 
5.ansistrlastchar('你好')结果是“好”。如果有半个汉字出现,返回这半个汉字。二者字符串长度分别为2和1。 
6.comparestr  - 区分大小写 
7.comparetext - 不区分大小写 
8.stringreplace(const s, oldpattern, newpattern: string;flags: treplaceflags): string;
字符串替换函数,需要引用sysutils单元
rfreplaceall:全部替换 
rfignorecase:忽略大小写
使用方法lg:
  str:='01231142211 :655767';//需要把:替换成----
s:=stringreplace(str,':','----',[rfreplaceall]);
for example:

var
astr: string;
begin
astr := 'this is a book, not a pen!';
showmessage(stringreplace (astr, 'a', 'two', []));   //this is two book, not a pen!只替换了第一个符合的字
showmessage(stringreplace (astr, 'a', 'two', [rfreplaceall]));
//this is two book, not two pen!替换了所有符合的字
astr := 'this is a book, not a pen!';
showmessage(stringreplace (astr, 'a', 'two', [rfreplaceall]));   //this is two book, not a pen!只替换了符合的字(小写a)
showmessage(stringreplace (astr, 'a', 'two', [rfreplaceall, rfignorecase]));   //this is two book, not two pen!不管大小写替换了所有符合的字
end;

9.delete 是删除一个 字符串中的 某部分字符
用法是 delete(str,//被删除的字符串 
              index,//从第几个字符开始删除
              count //删除几个
              );
delete(s, 2, 2); 就是从s中的第二个开始删除,删除2个字符即2、3.所以结果是145. 
////////////////////////////////////////////////////////
leftstr, midstr, rightstr的介绍
这几个函数都包含在strutils中,所以需要uses strutils; 
假设字符串是 dstr := ’delphi is the best’, 那么 
leftstr(dstr, 5) := ’delph’ 
midstr(dstr, 6, 7) := ’i is th’ 
rightstr(dstr, 6) := ’e best’



8.{判断字符是否是数字} 
function isdigit(ch: char): boolean; 
begin 
  result := ch in ['0'..'9']; 
end; 

9、{判断字符是否是大写字符} 
function isupper(ch: char): boolean; 
begin 
  result := ch in ['a'..'z']; 
end; 
10、{判断字符是否是小写字符} 
function islower(ch: char): boolean; 
begin 
  result := ch in ['a'..'z']; 
end; 
11、{转换为大写字符} 
function toupper(ch: char): char; 
begin 
  result := chr(ord(ch) and $df); 
end; 
12、{转换为小写字符} 
function tolower(ch: char): char; 
begin 
  result := chr(ord(ch) or $20); 
end; 
{ capitalizes first letter of every word in s } 

function proper(const s: string): string; 
var 
  i: integer; 
  capitalizenextletter: boolean; 
begin 
  result := lowercase(s); 
  capitalizenextletter := true; 
  for i := 1 to length(result) do 
  begin 
    if capitalizenextletter and islower(result[i]) then 
      result[i] := toupper(result[i]); 
    capitalizenextletter := result[i] = ' '; 
  end; 
end; 
//////////////////////////////////////////////////////////// 
13.{返回两个子字符串之间字符的个数} 
function p2pcount( s, ss1, ss2 : string ): integer; 
var i, j, slen : integer; 
begin 
   i := pos( ss1, s ); 
   j := pos( ss2, s ); 
   slen := length(ss2); 
   if j >= i then result := j - i + slen else result := 0; 
end; 
14.{更快速的字符查询,快40%} 
function scanstr(toscan: pchar; sign: char):pchar; 
begin 
  result:= nil; 
  if toscan <> nil then 
    while (toscan^ <> #0) do begin 
      if toscan^ = sign then begin 
        result:= toscan; 
        break; 
       end; 
     inc(toscan); 
    end; 
end; 
///////////////////////////// 
15.替换字符串中子串的函数,他可以从字符串中找出指定子串,并替换为另一子串。 
function replacing(s,source,target:string):string; 
var site,strlen:integer; 
begin 
{source在s中出现的位置} 
site:=pos(source,s); 
{source的长度} 
strlen:=length(source); 
{删除source字符串} 
delete(s,site,strlen); 
{插入target字符串到s中} 
insert(target,s,site); 
{返回新串} 
replacing:=s; 
end; 
/////////////////////// 
另两个替换字符串中子串的函数 
function repl_substr( sub1, sub2, s: string ): string; 
var i: integer; 
begin 
   repeat 
     i := pos( sub1, s ) ; 
     if i > 0 then begin 
       delete( s, i, length(sub1)); 
       insert( sub2, s, i ); 
     end; 
   until i < 1; 
   result := s; 
end; 
function replacetext(const s,replacepiece,replacewith: string):string; 
var position: integer; 
    tempstr: string; 
begin 
  position := pos(replacepiece,s); 
  if position > 0 then begin 
    tempstr := s; 
    delete(tempstr,1,position-1+length(replacepiece)); 
    result := 
copy(s,1,position-1)+replacewith+replacetext(tempstr,replacepiece,replacewith) 
  end else result := s; 
end; 
//////////////////////// 
替换全部子字符串的函数 
  function replacesub(str, sub1, sub2: string): string; 
    var 
    apos: integer; 
    rslt: string; 
  begin 
    apos := pos(sub1, str); 
    rslt := ''; 
    while (apos <> 0) do begin 
      rslt := rslt + copy(str, 1, apos - 1) + sub2; 
      delete(str, 1, apos + length(sub1)); 
      apos := pos(sub1, str); 
    end; 
    result := rslt + str; 
  end; 
///////////////////////// 
在字符串左右填充指定数量的指定字符 
function ut_padstring(instring :string; maxlength :integer; padchar :char; 
left :boolean) :string; 
begin 
  result := instring; 
  while (length(result) < maxlength) do 
    if (left) then 
      result := padchar + result 
    else 
      result := result + padchar; 
end; 
///////////////////////////////////// 
提取字符串中指定子字符串前的字符串 
function before ( string ; var s:string ) : string ; < /span>
  var 
  f : word ; 
begin 
  f := pos (src,s) ; 
  if f=0 then 
    before := s 
   else 
    before := copy(s,1,f-1) ; 
end ; 
////////////////////////////////// 
提取字符串中指定子字符串后的字符串 
function after ( string ; var s:string ) : string ; < /span>
  var 
  f : word ; 
begin 
  f := pos (src,s) ; 
  if f=0 then 
    after := '' 
   else 
    after := copy(s,f+length(src),length(s)) ; 
end ; 
//////////////////////////////////// 
判断字符串是否可以转换为整数 
function isintstr(const s: string): boolean; 
begin 
  result:=strtointdef(s,0)=strtointdef(s,1); 
end; 
////////////////////////////////////// 
从字符串中删除指定字符串 
procedure removeinvalid(what, where: string): string; 
  var 
  tstr: string; 
begin 
  tstr:=where; 
  while pos(what, tstr)>0 do 
    tstr:=copy(tstr,1,pos(what,tstr)-1) + 
       copy(tstr,pos(what,tstr)+length(tstr),length(tstr)); 
  result:=tstr; 
end; 
用法: 
  newstr:=removeinvalid('<invalid>','this <invalid> is my string and i wan to 
       remove the word <invalid>'); 
/////////////////////////////////////////// 
根据某个字符分割字符串的函数 
procedure separateterms(s : string;separator : char;terms : tstringlist); 
{ this browses a string and divide it into terms whenever the given 
  separator is found. the separators will be removed } 
  var 
  hs : string; 
  p : integer; 
begin 
  terms.clear; // first remove all remaining terms 
  if length(s)=0 then   // nothin' to separate 
    exit; 
  p:=pos(separator,s); 
  while p<>0 do 
  begin 
    hs:=copy(s,1,p-1);   // copy term 
    terms.add(hs);       // add to list 
    delete(s,1,p);       // remove term and separator 
    p:=pos(separator,s); // search next separator 
  end; 
  if length(s)>0 then 
    terms.add(s);        // add remaining term 
end; 
========== 
= 用  法 
========== 
var 
terms : tstringlist; 
i : integer; 
const 
teststr = '1st term;2nd term;3rd term'; 
begin 
  terms:=tstringlist.create; 
  separateterms(teststr,';',terms); 
  for i:=0 to terms.count-1 do 
    showmessage(terms.strings[i]); 
  terms.free; 
end; 
///////////////////////////// 
根据一组字符分割字符串的函数 
type 
charset = set of char; 
var 
f : text; 
s : string; 
procedure writestringsplitted(var s: string; separators: charset); 
var 
a,e : integer;  {anfang und ende des w鰎tchens} 
begin 
a := 1; 
for e := 1 to length(s) do 
  if s[e] in separators then begin 
   writeln(copy(s, a, e-a)); 
   a := e + 1; 
  end; 
  writeln(copy(s, a, e-a+1)); 
end; 
begin 
assign(f, 'c:/dingsbums/text.txt'); 
reset(f); 
while not eof(f) do begin 
  readln(f,s); 
  writestringsplitted(s, [':', ',']); 
end; 
close(f); 
end. 
////////////////////////////////////////////////// 
{===============================================================} 
{ 函数  : resultstring = hextobin(hexstring) 
{ 目的   : 把十六进制字符串转换为二进制字符串 
{ 
{===============================================================} 
{ 函数  : resultinteger = hexchartoint(hexchar) 
{ 目的   : 转换一个十六进制字符为整数 
{===============================================================} 
{ 函数  : resultstring = hexchartobin(hexchar) 
{ 目的   : 转换一个十六进制字符为二进制字符串 
{===============================================================} 
{ 函数  : resultinteger = pow(base,power) 
{ 目的   : 指数函数 
{===============================================================} 
{ 函数  : resultinteger = binstrtoint(binstring) 
{ 目的   : 把二进制字符串转换为整数 
{===============================================================} 
{ 函数  : resultstring = decodesms7bit (pdustring) 
{ 目的   : 解码一个7-bit sms (gsm 03.38) 为ascii码 
{===============================================================} 
{ 函数  :  resultstring = reversestr (sourcestring) 
{ 目的   : 反转一个字符串 
{===============================================================} 
unit binhextools; 
interface 
function hextobin(hexnr : string): string; 
function hexchartoint(hextoken : char):integer; 
function hexchartobin(hextoken : char): string; 
function pow(base, power: integer): integer; 
function binstrtoint(binstr : string) : integer; 
function decodesms7bit(pdu : string):string; 
function reversestr(sourcestr : string) : string; 
implementation 
uses sysutils, dialogs; 
function hexchartoint(hextoken : char):integer; 
begin 
  {if hextoken>#97 then hextoken:=chr(ord(hextoken)-32); 
  { use lowercase aswell } 
  result:=0; 
  if (hextoken>#47) and (hextoken<#58) then       { chars 0....9 } 
     result:=ord(hextoken)-48 
  else if (hextoken>#64) and (hextoken<#71) then  { chars a....f } 
     result:=ord(hextoken)-65 + 10; 
end; 
function hexchartobin(hextoken : char): string; 
var divleft : integer; 
begin 
    divleft:=hexchartoint(hextoken);   { first hex->bin } 
    result:=''; 
                                       { use reverse dividing } 
    repeat                             { trick; divide by 2 } 
      if odd(divleft) then             { result = odd ? then bit = 1 } 
        result:='1'+result             { result = even ? then bit = 0 } 
      else 
        result:='0'+result; 
      divleft:=divleft div 2;       { keep dividing till 0 left and length = 4 } 
    until (divleft=0) and (length(result)=4);      { 1 token = nibble = 4 bits } 
end; 
function hextobin(hexnr : string): string; 
{ only stringsize is limit of binnr } 
var counter : integer; 
begin 
  result:=''; 
  for counter:=1 to length(hexnr) do 
    result:=result+hexchartobin(hexnr[counter]); 
end; 
function pow(base, power: integer): integer; 
var counter : integer; 
begin 
  result:=1; 
  for counter:=1 to power do 
    result:=result*base; 
end; 
function binstrtoint(binstr : string) : integer; 
var counter : integer; 
begin 
  if length(binstr)>16 then 
    raise erangeerror.create(#13+binstr+#13+ 
            'is not within the valid range of a 16 bit binary.'+#13); 
  result:=0; 
  for counter:=1 to length(binstr) do 
      if binstr[counter]='1' then 
        result:=result+pow(2,length(binstr)-counter); 
end; 
function decodesms7bit(pdu : string):string; 
var octetstr : string; 
    octetbin : string; 
    charbin  : string; 
    prevoctet: string; 
    counter  : integer; 
    counter2 : integer; 
begin 
  prevoctet:=''; 
  result:=''; 
  for counter:=1 to length(pdu) do 
    begin 
      if length(prevoctet)>=7 then     { if 7 bit overflow on previous } 
        begin 
          if binstrtoint(prevoctet)<>0 then 
            result:=result+chr(binstrtoint(prevoctet)) 
          else result:=result+' '; 
          prevoctet:=''; 
        end; 
      if odd(counter) then            { only take two nibbles at a time } 
        begin 
          octetstr:=copy(pdu,counter,2); 
          octetbin:=hextobin(octetstr); 
          charbin:=''; 
          for counter2:=1 to length(prevoctet) do 
            charbin:=charbin+prevoctet[counter2]; 
          for counter2:=1 to 7-length(prevoctet) do 
            charbin:=octetbin[8-counter2+1]+charbin; 
          if binstrtoint(charbin)<>0 then result:=result+chr(binstrtoint(charbin)) 
            else result:=result+' '; 
          prevoctet:=copy(octetbin,1,length(prevoctet)+1); 
        end; 
    end; 
end; 
function reversestr(sourcestr : string) : string; 
var counter : integer; 
begin 
  result:=''; 
  for counter:=1 to length(sourcestr) do 
    result:=sourcestr[counter]+result; 
end; 
end.  

转发于: