473,657 Members | 2,513 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

String buffer

Yet another useful code snippet!

This StringBuffer class is a FIFO for character data.

Example:
B = StringBuffer('H ello W')
B.append('orld! ')
print B.read(5) # 'Hello'
print B.read() # 'World!'

The append method appends a string to the end of the string buffer.
The read(n) method reads and removes n characters from the beginning
of the buffer. If n is omitted, it reads the entire buffer. To view
the first n characters of the string buffer, use peek:

print B.peek(5) # View first 5 characters

Or cast as a string to get the entire contents:

print str(B) # View entire buffer

The append and read methods are O(k), where k is the number of
characters appended or read.

# -------------------------------------------------------
# StringBuffer: A FIFO for string data.
# -------------------------------------------------------

class Deque:
"""A double-ended queue."""
def __init__(self):
self.a = []
self.b = []
def push_last(self, obj):
self.b.append(o bj)
def push_first(self , obj):
self.a.append(o bj)
def partition(self) :
if len(self) > 1:
self.a.reverse( )
all = self.a + self.b
n = len(all) / 2
self.a = all[:n]
self.b = all[n:]
self.a.reverse( )
def pop_last(self):
if not self.b: self.partition( )
try: return self.b.pop()
except: return self.a.pop()
def pop_first(self) :
if not self.a: self.partition( )
try: return self.a.pop()
except: return self.b.pop()
def __len__(self):
return len(self.b) + len(self.a)

class StringBuffer(De que):
"""A FIFO for characters. Strings can be efficiently
appended to the end, and read from the beginning.

Example:
B = StringBuffer('H ello W')
B.append('orld! ')
print B.read(5) # 'Hello'
print B.read() # 'World!'
"""
def __init__(self, s=''):
Deque.__init__( self)
self.length = 0
self.append(s)
def append(self, s):
n = 128
for block in [s[i:i+n] for i in range(0,len(s), n)]:
self.push_last( block)
self.length += len(s)
def prepend(self, s):
n = 128
blocks = [s[i:i+n] for i in range(0,len(s), n)]
blocks.reverse( )
for block in blocks:
self.push_first (block)
self.length += len(s)
def read(self, n=None):
if n == None or n > len(self): n = len(self)
destlen = len(self) - n
ans = []
while len(self) > destlen:
ans += [self.pop_first( )]
self.length -= len(ans[-1])
ans = ''.join(ans)
self.prepend(an s[n:])
ans = ans[:n]
return ans
def peek(self, n=None):
ans = self.read(n)
self.prepend(an s)
return ans
def __len__(self): return self.length
def __str__(self): return self.peek()
def __repr__(self): return 'StringBuffer(' + str(self) + ')'
- Connelly Barnes
Jul 18 '05 #1
0 2625

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

17
6530
by: Axel | last post by:
Hiho, here my Newbie question (Win32 GUI): I'm reading a file in binary mode to a char* named buffer. I used malloc(filesize) to make the needed space avaiable. The filedata in the buffer seems to be ok..I can write the variable buffer back to a file and the contents is ok. So I think until here all goes fine... But now I want write the buffer contents to a Memo-Box for displaying.
51
8258
by: Alan | last post by:
hi all, I want to define a constant length string, say 4 then in a function at some time, I want to set the string to a constant value, say a below is my code but it fails what is the correct code? many thx!
9
7124
by: rsine | last post by:
I have developed a program that sends a command through the serial port to our business system and then reads from the buffer looking for a number. Everything worked great on my WinXP system, but when I tried the program on the Win98 system it will be running on, I get the following error: Cast from string "2076719" to type 'Long' is not valid I am not sure why I only get this error on the Win98 system or how to go about correcting...
1
6262
by: mdefoor | last post by:
I've written the following sample to split a string into chunks. Is this the right approach or is there perhaps a better way to accomplish getting chunks of a string? #include <stdio.h> #include <string.h> #define BUFSIZE 10 int main(int argc, char *argv) {
6
5665
by: Erik | last post by:
Hello, For many years ago I implemented my own string buffer class, which works fine except assignments - it copies the char* buffer instead of the pointer. Therefore in function calls I pass "const char*" and get the result in a parameter by reference "MyString& result". I'd like to move to nicer strings. In order to keep platform/compiler independence I consider std:string as the replacement. While googling I managed to read some...
9
1923
by: Michael D. Ober | last post by:
OK, I can't figure out a way to optimize the following VB 2005 code using StringBuilders: Public Const RecSize as Integer = 105 Private buffer As String Public Sub New() init End Sub Public Sub New(ByVal value As String)
3
20258
by: Jim Langston | last post by:
Is it possible to initialize a std::string with a character array, not neccessarily null terminated? I.E. Given something like this: char buffer; buffer = 0x01; buffer = 0x00; buffer = 'A'; buffer = 'B'; buffer = 'C';
3
2080
by: Benny the Guard | last post by:
I have a comma delimited file to parse up. So I figured I will go line by line and parse them up. Now efficiency is the top priority here. So I figure I can use the old-school C approach or use std::string. The way I see it I could (assuming infile is a valid std::ifstream) char buffer ; while (!infile.eof () && !infile.bad ()) { // Get the next line in the file infile.getline (buffer, 4095); // If fail bit is set it means we...
14
2158
by: Aman JIANG | last post by:
hi i need a fast way to do lots of conversion that between string and numerical value(integer, float, double...), and boost::lexical_cast is useless, because it runs for a long time, (about 60 times slower than corresponding C functions) it's too expensive for my program. is there any way( library?) to do this fast and safely, please ?
17
2147
by: let_the_best_man_win | last post by:
How do I print a pointer address into a string buffer and then read it back on a 64 bit machine ? Compulsion is to use string (char * buffer) only. printing with %d does not capture the full 64-bits of the pointer. does %l exist in both printf and scanf for this purpose ?
0
8324
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8740
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8513
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7352
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6176
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5642
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4330
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1970
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1733
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.