Re: [Vala] Problem with strings



On Sun, 2008-04-13 at 18:27 +0200, Olivier Rossiny wrote:
I'm trying to code with Vala. In fact to rewrite a C piece of code.

But this piece uses pointer arithmetic inside strings. Are Vala-strings 
unmutable ?

Yes, strings are usually considered immutable in Vala.

if I write this, I get an error:

string a = "baer";

a[1] = 'e';

stdout.println("%s\n", a);

but a vala string is a char* if I look at the C version ... so why isn't 
it allowed ? and, what is the solution ?

One reason why it's not allowed is that Vala strings are encoded in
UTF-8, which uses a variable number of bytes per character. This means
that replacing a single character as in your example might require
resizing the string, which we don't want to happen implicitly.

There are two possibilities how to modify strings in Vala. The
recommended way is to use the GLib.StringBuilder class, which is a
binding for GString. The other possibility is to use raw pointers just
like in C, however, you have to care about encoding and memory
management yourself, then.

        char* str_ptr = new char[64];
        str_ptr[0] = 'e';
        string str = (string) str_ptr;
        delete str_ptr;

Jürg




[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]