HOW TO Create a Simple String library in C language

How many of you, at the beginning of the lovely approach to the C language, have continuously struggled to get used to strings, pointers and other low-level instructions?

I already know the answer… A LOT (me too).

Generally the first very moment is when you have to deal with dynamically managed resources, in particular, strings.

Today I’ll try to do my best to give you some little explainations on how to create a C string library.

We are talking about c strings or CString library.

I wrote this library some time ago, to easier my life with strings, in a projects where strings were everywhere.

Of course, if you’re a low-level-stuff lover (like me), use this as a way of inspiration to create some bigger utilities!

So, why CString could be useful?

As you know, if you want to create a dynamic string in C, you have to:

And when you finish with it, you should take a:

if you need to.

Okay, it seems easy, it’s not a problem writing two lines of code, isn’t it?

What if you don’t know how long is the string?

If you use the classical approach, you will assume a maximum length and you’ll go with it. Sure, but you’ll waste a lot of memory if you are working on a big project!

What if you forgot to add the plus byte to store the string terminator?

When you’ll access that string, C will read everything, from the string content to pure garbage, casuing most of times some illegal accesses and crashes.

These won’t seem to you serious problems, but when you’ll have to realise some big projects, trust me, they mess up everything.

If you are interested: HOW TO Speed up your Android keyboard!

Here comes CString.

It’s easy, it implements a string data structure, an input method and a way to store integers in dynamic strings.

At the moment it’s not available neither in .dll nor a static .a, but you can simply import the file in your projects.

You can find CString code right here on github

As you can see, it’s not that hard to implement some higher-level methods to easier your life!

When I thought about C++ String, I told to my self: “Why not having it in C?”.. and tada, yes it’s minimal and perhaps can have some bugs, but it works.

If you find something wrong with it, you have some way to improve it, or something not clear, do not esitate to create a pull request on github or comment here!

This is also the beauty of open source!

Leave a Reply

Your email address will not be published.