TStringHelper does not return correct results

I use TStringHelper in a Win32 application, but when I try to access a specific char or get a substring, the return values ​​do not match. If I use equivalent old string functions.

 {$APPTYPE CONSOLE} {$R *.res} uses System.SysUtils; var i : Integer; s : string; begin try i:=12345678; Writeln(i.ToString().Chars[1]); // returns 2 Writeln(i.ToString().Substring(1)); //returns 2345678 s:=IntToStr(i); Writeln(s[1]); //returns 1 Writeln(Copy(s,1,Length(s)));//returns 12345678 except on E: Exception do Writeln(E.ClassName, ': ', E.Message); end; Readln; end. 

Question: Why are TStringHelper functions not equivalent to old string functions?

+4
source share
2 answers

This is because all methods and properties of System.SysUtils.TStringHelper are a zero-based index, this helper was a compiler with {$ ZEROBASEDSTRINGS ON} . You can find more information in the System.SysUtils.TStringHelper documentation.

+11
source

TStringHelper functions are based on 0, not 1. Based on related documents for TStringHelper.Chars ( highlight ):

Access to individual characters in this string with a null value .

From the link for TStringHelper.SubString (again, my emphasis ):

Returns a substring starting at the StartIndex position and optionally ending at the StartIndex + Length position, if specified, from this string 0 .

The sample code from the Chars link also shows a loop running from 0 to Length - 1 , instead of the usual string loop, which runs from 1 to Length(string) (comment):

 var I: Integer; MyString: String; begin MyString := 'This is a string.'; for I:= 0 to MyString.Length - 1 do // Note start and end of loop condition Write(MyString.Chars[I]); end. 
+4
source

Source: https://habr.com/ru/post/1490830/


All Articles