header image
Home arrow Programming arrow String Manipulation
String Manipulation

When using text variables are usually declared as Strings. A number of component properties are also string (text) values. For example Button1.Caption or Edit1.Text.

For example sSourceText can be declared as String under var.
sSourceText := ‘The man walks’

Take note that each character in a String variable can be referred to by using an index. The character sSourceText[2] would for instance be 'h'.

1 2 3 4 5 6 7 8 9 10 11 12 13
T h e   m a n   w a l k s

Even the spaces therefore has index values (see characters 4 and 8 above).


Furthermore Delphi has a number of prewritten functions and procedures that can be used to get properties of String variables or to manipulate the variables. Therefore to:

  • Determine the position of a piece of a text within a string
    IntegerVariable := Pos(StrToBeFound, SourceText);
    For example: iX := Pos (‘m’, sSourceText);
    {The value of iX is now: 5}
     
  • Display a certain character within a string using square brackets at the end of a variable.
    StringVariable := SourceText[CharacterPosition];
    For example: sNewText := sSourceText[2];
    {The value of sNewText is now: ‘h’}
     
  • Display a certain section of text within a string.
    For example: StringVariable := Copy(SourceText, BeginPosition, Length);
    sNewText := Copy(sSourceText, 5, 3);
    {The value of sNewText is now: ‘man’}
     
  • Insert a certain section of text within a string.
    For example: Insert(InsertText, SourceText, Position);
    Insert(‘big ’, sSourceText, 5);
    {The value of sSourceText is now: ‘The big man walks’}
     
  • Remove a certain section of text within a string.
    For example: Delete(SourceText, Position, Length);
    Delete(sSourceText, 5, 4);
    {The value of sSourceText is now: ‘The walks’}
     
  • Determine the length of a string.
    For example: IntegerVariable := Length(SourceText);
    iX := Length(sSourceText);
    {The value of iX is now: 13}
     
  • Change the whole string to lowercase.
    For example: LowerCase(SourceText);
    LowerCase(sSourceText);
    {The value of sSourceText is now: ‘the man walks’}
     
  • Change the whole string to uppercase.
    For example: UpperCase(SourceText);
    UpperCase(sSourceText);
    {The value of sSourceText is now: ‘THE MAN WALKS’}
    Take note: Use UpCase for Char type.
Polls
Which computer language (apart from Java and Delphi) would you like to study?
  
Who's Online
We have 10 guests online
Statistics
Members: 2
News: 41
Web Links: 4
Visitors: 452181