Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

delphi 2009 cast to string length 2

looking how to suppress a warning from the compiler that says possible data loss,

st:= copy(str,0,2);

where st is string[2] and str has more then 2 chars.

and copy is defied as from str return a new string that is a subset from 0 , 2 places.

like image 550
none Avatar asked Jan 29 '26 17:01

none


2 Answers

This will suppress the warning, but beware the underlying issue is still there: Converting from Unicode to AnsiString can cause lose of data.

st := ShortString(Copy(str,1,2));

And don't forget Delphi stings are 1-based, the first char in the string is 1, not 0.

like image 129
Cosmin Prund Avatar answered Jan 31 '26 09:01

Cosmin Prund


If you just write:

st := shortstring(str);

The compiler will do the work for you.

It will cut str content to fit the maximum length of st. So if st is defined as st: string[2]; if will retrieve only the 2 first characters of str.

But you may loose non ascii encoded characters in str (not a problem if it does contain only English text).

like image 38
Arnaud Bouchez Avatar answered Jan 31 '26 09:01

Arnaud Bouchez



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!