Best way to store a string?

  • (2 Pages)
  • +
  • 1
  • 2

18 Replies - 2341 Views - Last Post: 29 July 2010 - 11:25 AM Rate Topic: -----

#1 j33h4d  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 75
  • Joined: 16-March 10

Best way to store a string?

Posted 28 July 2010 - 01:32 PM

Hey guys,

I'm familiar with Java. To be honest, I make a big jump to dive into C programming. It offers less help in many things which really challenge my logic thinking. :P

BTW, I am looking for a much flexible way to store a string. Basically, a string is a combination of chars. So, this can be done by using char array which my lecturer asked me to use. The problem is, in some cases, I might either meet a condition where i need more location in runtime or i have unused locations which are such a waste. so, do there any method which i hope to be much flexible to store a string?

btw, my lecturer ever mentioned about calloc... i did searched about it but i found nothing is interesting. maybe i don't have a strong understanding on the concept applied for calloc function. it seems like it's doing the same thing like the normal way i declare an array. the only different, it uses pointer instead of the real data.

can anyone tell me the best method you use to solve this problem? :sleepy:

Is This A Good Question/Topic? 0
  • +

Replies To: Best way to store a string?

#2 Cuzzie  Icon User is offline

  • D.I.C Regular
  • member icon

Reputation: 72
  • View blog
  • Posts: 341
  • Joined: 16-July 10

Re: Best way to store a string?

Posted 28 July 2010 - 01:44 PM

Wait, are you talking about C or C++? If it's C, then if not mistaken, the only way to store it is by using char arrays... however, in C++, there's a string class for it.
Was This Post Helpful? 0
  • +
  • -

#3 j33h4d  Icon User is offline

  • D.I.C Head

Reputation: 2
  • View blog
  • Posts: 75
  • Joined: 16-March 10

Re: Best way to store a string?

Posted 28 July 2010 - 02:12 PM

i'm talking about C... not C++ :)

View Postorangcacat, on 28 July 2010 - 12:44 PM, said:

Wait, are you talking about C or C++? If it's C, then if not mistaken, the only way to store it is by using char arrays... however, in C++, there's a string class for it.

Was This Post Helpful? 0
  • +
  • -

#4 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: Best way to store a string?

Posted 28 July 2010 - 02:50 PM

Quote

so, do there any method which i hope to be much flexible to store a string?
Nothing natively. You've just discovered one reason why C is a pain to do any string manipulation in.

The usual solution is to pick a better language. Like C++. Ok, but what if you really had to use C? You would have to implement the entire abstraction yourself. Such an abstraction needs to dynamically allocate and free memory. It acquires memory as needed. If you need to add more to the string, this abstraction acquires even more memory, and so on.

Quote

it seems like it's doing the same thing like the normal way i declare an array. the only different, it uses pointer instead of the real data.
The reason is that if you allocate on the stack, you do not control the lifetime. You need to dynamically allocate and free memory, right? Well, to do that, you need to control allocation in the first place. That's what malloc/calloc/realloc/free are for.
Was This Post Helpful? 0
  • +
  • -

#5 pchapin  Icon User is offline

  • New D.I.C Head

Reputation: 34
  • View blog
  • Posts: 43
  • Joined: 23-July 10

Re: Best way to store a string?

Posted 28 July 2010 - 02:58 PM

View Postj33h4d, on 28 July 2010 - 01:12 PM, said:

i'm talking about C... not C++ :)


As you said C does not provide much help in this regard; you have to take care of the dynamic allocation of strings yourself. However, you can hide the problem inside an abstract data type. Essential you implement a C++ class using just C's features. Some of the details that a C++ compiler would do for you become exposed but the execution efficiency should be at least as good.

To outline the idea start with a header file

#ifndef STR_H
#define STR_H

typedef struct {
   char *buffer;          // Dynamically allocated space.
   int   current_length;  // Number of real characters.
   int   capacity;        // Overall size of the buffer.
} string;

// Invariants:
// 1. buffer == NULL only if object in error state.
// 2. capacity > 0
// 3. current_length < capacity
//
// At all times the string is null terminated.

int make_string_empty(string *object);
int make_string_ch(string *object, char ch, int count);
int make_string_charp(string *object, const char *incoming);
void destroy_string(string *object);
// various other methods...
#endif



In each of the functions the first parameter points at the string object and plays the role of 'this' in a C++ method. You can, of course, come up with many other methods that would be appropriate. What I show above is just a start and just a suggestion.

The implementation file provides all the necessary code

#include "str.h"

#define INITIAL_CAPACITY 8

int make_string_empty(string *object)
{
  object->buffer = malloc(INITIAL_CAPACITY * sizeof(char));
  if( object_buffer == NULL ) return 0;  // Failure.
  object->capacity = INITIAL_CAPACITY;
  object->buffer[0] = '\0';              // Null terminate.
  object->current_length = 0;            // Empty string.
  return 1;                              // Success.
}

// etc for all the other methods.



It's a bit of work to set up but once done using dynamic strings in C is not too difficult. For example:

#include "str.h"

int main( void )
{
  string my_string;
  if( make_string_empty(&my_string) ) {
    // The string is valid. We can use it...

    destroy_string(&my_string);
  }
  return 0;
}



I leave it as an exercise to the reader to flesh this out to a fully functional dynamic string type for C. :)

This post has been edited by pchapin: 28 July 2010 - 03:00 PM

Was This Post Helpful? 2
  • +
  • -

#6 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1112
  • View blog
  • Posts: 4,619
  • Joined: 09-June 09

Re: Best way to store a string?

Posted 28 July 2010 - 03:08 PM

C++ offers flexablity with its use of STL containers. But in see you are given none of that. To be dynamic you must use calloc/malloc/realloc to allocate your strings during run time. You are allowed to use what is called a linked list which is a great concept on expanding memory dynamically. read Here
To be honest though, dont worry about allocating too much memory. This isnt the 20th century, were not using punch cards

This post has been edited by ImaSexy: 28 July 2010 - 04:07 PM

Was This Post Helpful? 1
  • +
  • -

#7 dorknexus  Icon User is offline

  • or something bad...real bad.
  • member icon

Reputation: 1256
  • View blog
  • Posts: 4,618
  • Joined: 02-May 04

Re: Best way to store a string?

Posted 28 July 2010 - 03:48 PM

Well in the 19th century we still hadn't figured out the whole electronic computer thing yet, let alone punch cards.
Was This Post Helpful? 0
  • +
  • -

#8 drhowarddrfine  Icon User is offline

  • D.I.C Regular

Reputation: 39
  • View blog
  • Posts: 275
  • Joined: 28-July 10

Re: Best way to store a string?

Posted 28 July 2010 - 04:15 PM

Um. Hm.

#include <string.h>

char *s;
s=strdup(pointer to string);


done.

This post has been edited by drhowarddrfine: 28 July 2010 - 04:19 PM

Was This Post Helpful? 0
  • +
  • -

#9 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1112
  • View blog
  • Posts: 4,619
  • Joined: 09-June 09

Re: Best way to store a string?

Posted 28 July 2010 - 04:21 PM

How does creating a string duplicate answer the OP's question?
Was This Post Helpful? 0
  • +
  • -

#10 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: Best way to store a string?

Posted 28 July 2010 - 04:21 PM

Two counterpoints:

strdup only, uh, duplicates. It doesn't offer an abstraction that the OP wants.

strdup is nonstandard.
Was This Post Helpful? 0
  • +
  • -

#11 drhowarddrfine  Icon User is offline

  • D.I.C Regular

Reputation: 39
  • View blog
  • Posts: 275
  • Joined: 28-July 10

Re: Best way to store a string?

Posted 28 July 2010 - 04:24 PM

I'm not sure I understand the question properly. If that's not it, then:

char *s;

s=malloc(strlen(pointer to string));
strcpy(s,[pointer to string]);


But I still may not understand what he's getting at. I'm tired.

View PostOler1s, on 28 July 2010 - 04:21 PM, said:

strdup is nonstandard.

strdup is POSIX compliant.

This post has been edited by drhowarddrfine: 28 July 2010 - 04:29 PM

Was This Post Helpful? 0
  • +
  • -

#12 jjl  Icon User is offline

  • Engineer
  • member icon

Reputation: 1112
  • View blog
  • Posts: 4,619
  • Joined: 09-June 09

Re: Best way to store a string?

Posted 28 July 2010 - 04:34 PM

He wants to know how to dynamically expand or contract C strings to fit the desired amount of space needed. maybe you should actually read the OP's question...

Heres a pretty good thread on realloc
http://www.dreaminco...g-realloc-in-c/

This post has been edited by ImaSexy: 28 July 2010 - 04:36 PM

Was This Post Helpful? 0
  • +
  • -

#13 Oler1s  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1395
  • View blog
  • Posts: 3,884
  • Joined: 04-June 09

Re: Best way to store a string?

Posted 28 July 2010 - 04:36 PM

Quote

I'm not sure I understand the question properly.
The question is about a proper string abstraction, like C++ string, or that of Java or C# or any higher level language native string support. Which you aren't providing. All you are showing is how to copy C strings...

Quote

strdup is POSIX compliant.
POSIX standard != C standard.
Was This Post Helpful? 1
  • +
  • -

#14 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5943
  • View blog
  • Posts: 12,871
  • Joined: 16-October 07

Re: Best way to store a string?

Posted 28 July 2010 - 05:03 PM

How exactly do you think Java implements that String class?

// from - http://www.docjar.com/html/api/java/lang/String.java.html
137       private final char[] value;
139       private final int offset;
141       private final int count;
156       /**
157        * Creates an empty string.
158        */
159       public String() {
160           value = new char[0];
161           offset = 0;
162           count = 0;
163       }



C++?
// from - http://gcc.gnu.org/viewcvs/trunk/libstdc%2B%2B-v3/include/bits/basic_string.h?view=markup
1756      const _CharT*
1757      c_str() const
1758      { return _M_data(); }



C is a very simple language. It allows you to construct the system you desire with only the components you need. It requires some extra work or discipline or skill.

Strings, in particular, are usually just an array of characters. A contiguous block of memory IS the best way to store a string.

So, you allocate a string of the size you want. You want to add characters to it, you make a string the size you need and copy the values you need. And free the old value. This is the opposite of wasteful; you have full control over the storage requirements of your program.

If you think other languages somehow optimize storage without going through such steps, you're mistaken. Now you will begin to see more clearly the impact of your operational choices, without the obfuscation of a class wrapper.

So, what are you trying to do?

View PostOler1s, on 28 July 2010 - 03:50 PM, said:

The usual solution is to pick a better language.


Most useless response ever. :P
Was This Post Helpful? 1
  • +
  • -

#15 drhowarddrfine  Icon User is offline

  • D.I.C Regular

Reputation: 39
  • View blog
  • Posts: 275
  • Joined: 28-July 10

Re: Best way to store a string?

Posted 28 July 2010 - 08:09 PM

Now I don't think I misread his q at all. And baavgai said what I was going to say. I'm sure my code does what he wants.

This post has been edited by drhowarddrfine: 28 July 2010 - 08:11 PM

Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2