user1291092
user1291092

Reputation: 113

How do I count characters in a string, excluding certain types?

I need to determine the total number of characters in a textbox and display the value in a label, but all whitespace need to be excluded.

Here is the code:

var     
sLength : string;
i : integer;
begin
     sLength := edtTheText.Text;
     slength:= ' ';
     i := length(sLength);

     //display the length of the string
     lblLength.Caption := 'The string is ' +  IntToStr(i)  + ' characters long';

Upvotes: 5

Views: 8246

Answers (2)

az01
az01

Reputation: 2018

If you are using an Ansi version of Delphi you can also use a Lookup Table with something like

NotBlanks: Array[0..255] Of Boolean

A Bool in the array is set if the matching character is not a blank. Then In the loop you simply increment your counter

Count := 0;
For i := 1 To Length(MyStringToParse) Do
  Inc(Count, Byte(NotBlanks[ Ord(MyStringToParse[i]])) );

In the same fashion you can use a set:

For i := 1 To Length(MyStringToParse) Do
If Not (MyStringToParse[i] In [#1,#2{define the blanks in this enum}]) Then 
  Inc(Count).

Actually you have many ways to solve this.

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612784

You can count the non-white space characters like this:

uses
  Character;

function NonWhiteSpaceCharacterCount(const str: string): Integer;
var
  c: Char;
begin
  Result := 0;
  for c in str do
    if not Character.IsWhiteSpace(c) then
      inc(Result);
end;

This uses Character.IsWhiteSpace to determine whether or not a character is whitespace. IsWhiteSpace returns True if and only if the character is classified as being whitespace, according to the Unicode specification. So, tab characters count as whitespace.

Upvotes: 11

Related Questions