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';
First, we split the string by spaces in a. Then, take a variable count = 0 and in every true condition we increment the count by 1. Now run a loop at 0 to length of string and check if our string is equal to the word.
Let's start with a simple/naive approach: String someString = "elephant"; char someChar = 'e'; int count = 0; for (int i = 0; i < someString. length(); i++) { if (someString. charAt(i) == someChar) { count++; } } assertEquals(2, count);
Use str. count() to count the number of characters in a string except spaces. Use len(object) to get the length of a string object .
To do this, size() function is used to find the length of a string object. Then, the for loop is iterated until the end of the string. In each iteration, occurrence of character is checked and if found, the value of count is incremented by 1.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With