Страница 1 из 1
посимвольное чтение строки
Добавлено: 03.09.2015 11:55:55
sqrt314
Доброго времени, при считывании строки
Код: Выделить всё
z:=(Edit1.Text); // здесь вводим какое либо слово
d:=Length(z); // узнаем длину строки/слова
For i:=1 to d do
begin
//.................... выполнение операций с учетом какой символ попался
if z[a]= 'S' then ShowMessage(' S') ; // К примеру такой код
end;
Вот здесь то и возникает проблема если вводить кириллицу, то таким методом не удается прочитать посимвольно строку,так как на кириллицу отводиться 2 байта на символ вопрос подскажите как считать кириллицу посимвольно.?
Re: посимвольное чтение строки
Добавлено: 03.09.2015 12:03:39
Ism
Re: посимвольное чтение строки в кодировке UTF-8
Добавлено: 23.01.2018 21:16:04
Python
Возможно, моё решение кому-то пригодится, пусть даже и не автору вопроса:
Код: Выделить всё
unit Utf8Enumerator;
interface
Type
{ TUtf8Enumerator }
TUtf8Enumerator=class
private
fIndex,fLength:integer;
fData,
fCurrent:string;
public
property Current:string read fCurrent;
function MoveNext:boolean;
function GetEnumerator:TUtf8Enumerator;inline;
Constructor Create(const S:string);
end;
function Utf8Enum(const S:string):TUtf8Enumerator;inline;
implementation
{ TUtf8Enumerator }
function TUtf8Enumerator.MoveNext: boolean;
var
C:char;
begin
if fIndex>=fLength then begin
Result:=false;
exit;
end;
Inc(fIndex);
C:=fData[fIndex];
if ord(C) and $80=0 then begin // one-char length
Result:=true;
fCurrent:=C;
end else if ord(C) and $E0=$C0 then begin // two-char length
Result:=fIndex+1<=fLength;
if Result then begin
fCurrent:=C+fData[fIndex+1];
Inc(fIndex);
end;
end else if ord(C) and $F0=$E0 then begin // three-char length
Result:=fIndex+2<=fLength;
if Result then begin
fCurrent:=C+fData[fIndex+1]+fData[fIndex+2];
Inc(fIndex,2);
end;
end else if ord(C) and $F8=$F0 then begin // fourth-char length
Result:=fIndex+3<=fLength;
if Result then begin
fCurrent:=C+fData[fIndex+1]+fData[fIndex+2]+fData[fIndex+3];
Inc(fIndex,3);
end;
end else begin // invalid char
Result:=false;
end;
end;
function TUtf8Enumerator.GetEnumerator: TUtf8Enumerator;
begin
Result:=Self;
end;
constructor TUtf8Enumerator.Create(const S: string);
begin
inherited Create;
fData:=S;
fLength:=Length(S);
end;
function Utf8Enum(const S:string):TUtf8Enumerator;
begin
Result:=TUtf8Enumerator.Create(S);
end;
end.
Использование:
Код: Выделить всё
var
C,S:string;
begin
S:='Пиво';
For C in Utf8Enum(S) do
ShowMessage(C);
end;