Re: [GLib] How to get substrings?
- From: Iago Rubio <iago rubio hispalinux es>
- To: gtk-app-devel-list gnome org
- Subject: Re: [GLib] How to get substrings?
- Date: Tue, 09 Nov 2004 17:26:01 +0100
On Mon, 2004-11-08 at 12:31, Daniel Miralles GarcÃa wrote:
Hi, dudes!
I'm porting my old-style char* to gchar* (due to some SF's that appear
when I dont't printf("")).
I've been looking a few here and there, but found no function to get a
substring (I mean, from a string, get a substring between two characters
or even two positions). For instance:
Origin = "ABCDEFGH"
my_str = g_get_substring_beteen (origin, "D", "G");
and then my_str=="EF"
From memory:
/* all strings should be NULL terminated.
returns a newly allocated string or NULL */
gchar*
substring_between( gchar* haystack, gchar* needle1, gchar* needle2)
{
gchar* pos1;
gchar* pos2;
gchar* strcopy;
gchar* retval;
if( haystack == NULL || needle1 == NULL || needle2 == NULL )
return NULL;
strcopy = g_strdup(haystack);
pos1 = g_strrstr( (const gchar*) strcopy,
(const gchar*) needle1 );
if( pos1 == NULL) {
g_free(strcopy);
return NULL;
}
pos2 = g_strrstr( (const gchar*) pos1,
(const gchar*) needle2);
if( pos2 == NULL ) {
g_free(strcopy);
return NULL;
}
if( (pos1 += strlen(needle1)) >= pos2) {
g_free(strcopy);
return NULL;
}
*pos2 = '\0';
retval = g_strdup(pos1);
g_free(strcopy);
return retval;
}
I though making it, but I need some "look a character" function:
char mychar = g_get_char (origin, position);
or something like this...
...and then maybe appending a character to a string?
origin = g_strdup("hell");
g_string_append_char (origin, "o");
It should be g_string_append_string or
g_string_append_char(oring, 'o');
just to have origin -> "hello"...
gchar* string = g_strconcat( origin, "o", NULL );
// use string
g_free(string); // we no needed anymore
or,
gchar* // returns a newly allocated string or NULL
string_append_char( gchar* string, gchar character, gboolean free_old )
{
gchar* new_string;
g_return_val_if_fail(string != NULL, NULL);
new_string = g_strdup_printf("%s%c", string, character);
if( free_old ) g_free( string );
return new_string;
}
Any function in GLIB to do that?
Nope, but lots of helpers to implement it.
--
Iago Rubio
[
Date Prev][
Date Next] [
Thread Prev][
Thread Next]
[
Thread Index]
[
Date Index]
[
Author Index]