Character string as array

200 views
Skip to first unread message

olmor

unread,
Nov 1, 2010, 5:13:49 AM11/1/10
to Harbour Users
Hello!

Is there any way to access character strings as arrays in harbour?

F.e.
cStr:='abcde'
?cStr[1] // 'a'
?cStr[3] // 'c'

I know that this option exists but don't know how turn it on.

Regards, Oleg

Massimo Belgrano

unread,
Nov 1, 2010, 8:22:15 AM11/1/10
to Harbour Users
In Xharbour i think Strings may be indexed like arrays:
<StringExp>[<IndexExp>]
String as Array Index can also accepts a numeric as an assigned value:
<StringExp>[<IndexExp>] := 65 // Same as := 'A'
String Index and all String of 1 character length, automatically carry
a secondary CHAR type, which means they are also compatible with
numeric operations.
cVar := "hello"; cVar[1] -= 32 // -> "Hello"

try using xharbour compatibility library xhb..hbxhb

vatzct

unread,
Nov 1, 2010, 6:10:27 AM11/1/10
to harbou...@googlegroups.com
01.11.2010 11:13, olmor написав(ла):
Hi!

From \doc\xhb-diff.txt

### USING [] OPERATOR FOR STRING ITEMS ###
================================================
xHarbour supports using [] operator to access single characters in
string items. Harbour doesn't by default but it has strong enough
OOP API to allow adding such extension without touching core code
even by user at .prg level. It was implemented in Harbour in XHB.LIB.
This code can be compiled and executed by both compilers:
#ifndef __XHARBOUR__
#include "xhb.ch" // add xHarbour emulation to Harbour
#endif
proc main()
local s := "ABCDEFG"
? s, "=>", s[2], s[4], s[6]
s[2] := lower( s[2] )
s[4] := lower( s[4] )
s[6] := lower( s[6] )
?? " =>", s
return

Warning!. There is one difference in above implementation introduced
intentionally to Harbour. xHarbour never generates errors for wrong
indexes in [] operator used for string items but simply returns "",
f.e. add to above code:
? ">" + s[0] + "<", ">" + s[1000] + "<"
If [] operator is used for other type of items RTE is generated.
Harbour will generate RTE in all cases. If someone needs strict XHB
compatibility here then he should adopt code overloading [] operator
for strings in XHB.LIB for his own preferences removing the RTE.

Regards,
Alexey Myronenko

olmor

unread,
Nov 2, 2010, 5:21:47 AM11/2/10
to Harbour Users
Massimo, Alexey!

Thank you. It works now.

Regards, Oleg

Massimo Belgrano

unread,
Nov 2, 2010, 6:07:23 AM11/2/10
to harbou...@googlegroups.com
Post here your sample
so share your result with everybody

2010/11/2 olmor <ol...@mail.ru>:


> Massimo, Alexey!
>
> Thank you. It works now.
>
> Regards, Oleg
>

--
Massimo Belgrano

Reply all
Reply to author
Forward
0 new messages