Sorting TStringList by the first character after whitespace in Delphi
When working with strings in Delphi, you might encounter a scenario where you need to sort a TStringList not by the entire string, but by a specific part of it, such as the first character after whitespace. This can be useful when you have a list of full names and you want to sort them by last name. In this article, we'll explore how to achieve this using a custom sort function.
The Problem
You have a TStringList in Delphi containing full names (first name followed by last name, e.g., "John Smith"). You want to sort this list by last name, specifically by the first character after the space. Additionally, the strings may contain Unicode characters, such as Persian characters.
The Solution
To sort a TStringList by a specific part of the string, you can use the CustomSort method of TStringList. This method allows you to supply a custom compare function that compares two strings based on your specific requirements.
First, let's create a function that splits a full name into last name and the rest:
procedure SplitName(const Name: string; out Last, Rest: string);
var
P: Integer;
begin
P := Pos(' ', Name);
if P = 0 then begin
Last := Trim(Name);
Rest := '';
end else begin
Last := Trim(Copy(Name, P+1, MaxInt));
Rest := Trim(Copy(Name, 1, P-1));
end;
end;
Next, we'll implement the custom compare function:
function NameCompareFunc(List: TStringList; Index1, Index2: Integer): Integer;
var
Last1, Last2, Rest1, Rest2: string;
begin
SplitName(List[Index1], Last1, Rest1);
SplitName(List[Index2], Last2, Rest2);
Result := AnsiCompareText(Last1, Last2);
if Result = 0 then begin
Result := AnsiCompareText(Rest1, Rest2);
end;
end;
In this function, we first split the strings at index1 and index2 into last name and the rest. We then compare the last names using AnsiCompareText, which performs locale-aware comparison. If the last names are the same, we perform a secondary comparison on the rest of the name.
Finally, we can sort the TStringList using the custom compare function:
NameBuffer.CustomSort(NameCompareFunc);
Example
Here's an example demonstrating the usage of the custom compare function:
In this example, clicking the "Sort" button will add some full names to the NameBufferTStringList, sort it using the custom compare function, and display the sorted list in a TMemo component.
Conclusion
Sorting a TStringList by a specific part of the string, such as the first character after whitespace, can be achieved using the CustomSort method and a custom compare function. This approach allows you to sort strings based on your specific requirements, making it a powerful tool for handling complex sorting scenarios in Delphi.
Эта статья объясняет, как отсортировать TStringList в Дельфи по первому символу после пробела в строке, полезно для сортировки списка полных имен по фамилии.
Комментарии и вопросы
Получайте свежие новости и обновления по Object Pascal, Delphi и Lazarus прямо в свой смартфон. Подпишитесь на наш Telegram-канал delphi_kansoftware и будьте в курсе последних тенденций в разработке под Linux, Windows, Android и iOS
Материалы статей собраны из открытых источников, владелец сайта не претендует на авторство. Там где авторство установить не удалось, материал подаётся без имени автора. В случае если Вы считаете, что Ваши права нарушены, пожалуйста, свяжитесь с владельцем сайта.