How to count characters in a string, excluding certain types?

I need to determine the total number of characters in the text box and display the value in the label, but all spaces 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';
+5
source share
2 answers

You can count non-white space characters as follows:

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;

Used here Character.IsWhiteSpaceto determine if a character is a space. IsWhiteSpacereturns Trueif and only if the character is classified as whitespace, in accordance with the Unicode specification. Thus, tabs are considered spaces.

+10
source

If you are using a version of Delphi Ansi, you can also use a lookup table with something like

NotBlanks: Array[0..255] Of Boolean

Bool , .

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

:

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

.

0

All Articles