如何计算字符串中的字符,不包括某些类型?

时间:2012-09-17 15:29:36

标签: string delphi counting

我需要确定文本框中的字符总数并在标签中显示该值,但是需要排除所有空格。

以下是代码:

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

2 个答案:

答案 0 :(得分:11)

您可以像这样计算非空格字符:

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;

这使用Character.IsWhiteSpace来确定字符是否为空格。 IsWhiteSpace返回True当且仅当字符被分类为空格时,根据Unicode规范。因此,制表符被视为空格。

答案 1 :(得分:0)

如果您使用的是Ansi版本的Delphi,您也可以使用类似

的查找表
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).

实际上,你有很多方法可以解决这个问题。