Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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';
like image 972
user1291092 Avatar asked Sep 17 '12 15:09

user1291092


People also ask

How do you count specific occurrences of characters in a string?

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.

How do you count occurrences of character?

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);

How do you count the number of characters in a string except spaces in Python?

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 .

How do I count a specific character in a string in C++?

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.


1 Answers

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.

like image 138
David Heffernan Avatar answered Sep 24 '22 13:09

David Heffernan