String 변수값에서 숫자 혹은 문자를 골라내서 삭제할 수 있는 간단한 메서드
※ 소스코드 출처 : https://stackoverflow.com/questions/10838468/delete-numbers-from-a-string
Delete numbers from a String
I'd like to know how I can delete numbers from a String. I try to use StringReplace and I don't know how to tell the function that I want to replace numbers. Here's what I tried: StringReplace(mS...
stackoverflow.com
※ 숫자만 제거하기
function RemoveDecimal(const aString: string): string;
var
C:Char; Index:Integer;
begin
Result := '';
SetLength(Result, Length(aString));
Index := 1;
for C in aString do
begin
if not CharInSet(C, ['0' .. '9']) then
begin
Result[Index] := C;
Inc(Index);
end;
end;
SetLength(Result, Index-1);
end;
- for-in 문을 사용한것을 볼 수 있다.
* for-in 문은 [Delphi 2005] 버전 이상부터 사용할 수 있다.
위 코드에서 조건만 반대로 걸면 숫자가 아니라 문자만 제거를 할 수도 있다.
※ 문자만 제거하기
procedure RemoveChar(var s: string);
var
i, j: Integer;
pc: PChar;
begin
j := 0;
pc := PChar(@s[1]);
for i := 0 to Length(s) - 1 do
begin
if not (pc[i] in ['0'..'9']) then
Inc(j)
else
pc[i - j] := pc[i];
end;
SetLength(s, Length(s) - j);
end;
- 하위버전 호환성을 고려하여 for-in 문을 사용하지 않고 사용한 코드.
- 대신 매개변수를 var 타입으로 받고 있으므로, procedure로 구현하였다.
* String 타입의 매개변수 값 자체가 바뀌는 코드이므로, 사용에 주의가 필요하다.
'Delphi' 카테고리의 다른 글
[델파이/Delphi] Generic(제네릭) 간단 사용 예제 (0) | 2021.11.27 |
---|---|
[델파이/Delphi] TStringList - Delimiter & LineBreak, CommaText 예제 (1) | 2021.11.22 |
[델파이/Delphi] 열거형(Enum) 사용 예시 (0) | 2021.11.01 |
[델파이/Delphi] "Interface not supported" 에러 (ExcelExport) (0) | 2021.10.26 |
[Delphi/델파이] 최근 에러 조회하기 - GetLastError (0) | 2021.10.15 |