Delphi 分割字符串

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Delphi 分割字符串相关的知识,希望对你有一定的参考价值。

如果我想将下例一行字符串分割后显示批定字符到edit内,如何做
例:字符串为 'Delphi 电脑网络 其他编程语言'

怎么将Delphi输出到edit内呢?
上边我只是举个例子,我是想将第一个空格前的字符串取出来
在默认情况下并非知道第一空格前多少个字符.所以说用copy或者pos这两个函数没用的!这两个函数要知道字符串长度才行,可是我在先前是不知道的,只知道想取的是第一个空格前的字符串

delphi有个extrastring的函数用来分割字符串

Unit Classes

Syntax

Description < by specified null-terminated the of fill to ExtractStrings>

< is character quote if quoted in appear can characters that (Note quote. end final until inside when ignored are Separators separators. as treated always double) or (single and characters, newline returns, Carriage substrings. separating delimiters, used set>

< beginning at occur they Content parsing be>

< into parse> 如果我想分割以下字符串:
ABC|... DEF|#### GHI|"中华网URL|# www.china.com"

希望得到下面四个字符串:
1、ABC
2、DEF
3、GHI
4、中华网URL|# www.china.com

那么可以用下面的代码:

uses
Classes;
var
ASource: PChar;
AStr: String;
ACount: Integer;
AStrings: TStringList;
begin
ASource := \'ABC|... DEF|#### GHI|"中华网URL|# www.china.com"\';
AStrings := TStringList.Create;
try
ACount := ExtractStrings([\'|\'], [\' \',\'#\',\'.\'], ASource, AStrings);
do any further processing
//for AStr in AStrings do
// Writeln(AStr);
finally
AStrings.Free;
end;

Readln;
end.

< already strings any so ExtractStrings, cleared not The added. all which>< Strings added number returns>

ExtractStrings does not add empty strings to the list.

[E文看着比较累,还是中文一下吧]:

WhiteSpace 参数指定每个子串开头被忽略的字符s。
Content 参数就是被分割的“源”串了。
Strings 参数用于接收分割后的各个子串。它的原有内容不会被清空。别忘了对Strings进行Create哦。
另外,EctractStrings不会把空串放入Strings中去。

举个例子吧:

ExtractStrings(Separators: TSysCharSet; WhiteSpace: TSysCharSet; Content: PAnsiChar; Strings: TStrings): Integer;
参考技术A procedure TForm1.Button1Click(Sender: TObject);
var
tempStr: String;
DelimiterPos: Integer;
begin
tempStr:= 'Delphi 电脑网络 其他编程语言';
DelimiterPos:= Pos(' ', tempStr); //这句就知道长度了
tempStr:= Copy(tempStr, 0, DelimiterPos);
ShowMessage(tempStr);
end;
参考技术B 文字处理我的强项
var
tmpStr, tmpPosStr: string;
tmpInt: integer;
......
begin
......
tmpStr:= 'Delphi电脑网络 其他编程语言';//字串
tmpPosStr:= ' ';//分割符
tmpInt:= Pos(tmpPosStr, tmpStr);//分割符位置
if tmpInt>0 then
begin
Edit1.Text := copy(tmpStr,1,tmpInt);
Edit1.Text := copy(tmpStr,tmpInt,Length(tmpStr));
end;
......
end;

随手写的,没有编译过,如有手误或者其它错误包含一下

这是一个分割符,分成两个字串的例子,你可以自己改改改成其它例子
参考技术C edit1.text :=copy('Delphi电脑网络 其他编程语言',1,6);

以上是关于Delphi 分割字符串的主要内容,如果未能解决你的问题,请参考以下文章

Delphi里面字符分割函数是啥 如何分割以 为分割的字符串

Delphi 分割字符串

delphi 分割字符串求教

delphi string.split 按照任意字符串分割语句

delphi字符串分割和比大小

Delphi 分割字符串,很长的字符串。