Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations biv343 on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Strings and chars

Status
Not open for further replies.

MichaelHooker

Programmer
Mar 17, 2006
70
GB
OK, it's a dumb question. Delphi 7 PE, WinXP. A procedure in my latest project declares a variable N as a String.
The variable then gets its value from an index to another string, as in:

Code:
N := String[25];

N then goes through a lot of processing until it's time to put it back where it came from:

Code:
String[25] := N;

However, the compiler does not like this, reporting:
Code:
Incompatible types: 'Char' and 'String'
when it gets to the line where N is fed back in to the string. It doesn't mind taking the single character element out of the string and putting it into var N, it just doesn't like putting it back again.

I can get around this by declaring N and O as Char types in the first place, though I was also trying to use them for expressions like:
Code:
N := LeftStr(String, 5);
I'll just have to use different variables. I can see many other ways around this, and I'm not asking for solutions. I'm just puzzled as to why Delphi will assign a single character from one string to another string, but won't do the reverse. I can't find any StrToChar or CharToStr functions, so you would think that no user conversion is ever contemplated.

So what's going on here and why?

Many thanks.

Michael Hooker

 
this must work:

Code:
String[25] := N[1];

as N is defined as a string, delphi will do no length check on N, so even if N has a length of 1 delphi will throw the error...

/Daddy

-----------------------------------------------------
What You See Is What You Get
Never underestimate tha powah of tha google!
 
Specifically, it is because of default type promotions.

Given:
Code:
var s: string; c: char;

You can promote a char to a string (an array of char):
Code:
s := c;

but you cannot promote a string (many chars) to a (single) char:
Code:
c := s;  {error!}

Hope this helps.
 
Thank you both.

I understand what you're saying. It might have been handier if assigning a string to a Char resulted in the first character of the string being copied over and the rest ignored - in other words String[25] := N[1] without having to specify the "[1]". It just seems to me to be something Delphi should take care of automatically if the string N does only consist of one character, but as Daddy says, it doesn't check.

Thanks

Michael Hooker
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top