Re: GLib substr function



Am Fri, 10 Apr 2009 12:45:39 +0200
schrieb b0unc3 <daniele maio gmail com>:

> Hi all,
> 
> there is any implementation of a substr function in GLib ?
> 
> I mean :
> string = "hello world"
> g_*substr*(string,2,6)
> output = llo w

Hey b0unc3,

no, there isn't. Either you use a higher level language which has it or
you use low level functions in C.

For the sake of demonstration, it took me 2 minutes to write a simple
substring function in C that does what you want, have a look how it
works. :)

Yours,
    Christian
/* Copyright (c) 2009 Christian Dywan <christian twotoasts de>
   This code is licensed under the terms of the expat license */

/* gcc -o substr substr.c $(pkg-config --cflags --libs glib-2.0) -Wall -O1 -g */

#include <glib.h>

gchar *
g_substr (const gchar* string,
          gint         start,
          gint         end)
{
  gsize len = (end - start + 1);
  gchar *output = g_malloc0 (len + 1);
  return g_utf8_strncpy (output, &string[start], len);
}

int
main (int    argc,
      gchar* argv[])
{
  const gchar *string = "hello world";
  gchar *output = g_substr (string, 2, 6);
  g_print ("input: %s, output: %s\n", string, output);
  g_assert_cmpstr (output, ==, "llo w");
  g_free (output);

  return 0;
}


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