473,770 Members | 4,029 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to left pad a string with spaces?

If I have a string say:

myvar[128] = "This is a string";

How do I use sprintf to convert the string so it has 4 spaces padded on
the left like:

" This is a string";
Thanks!
Jun 27 '08 #1
41 12466
nospam <no@spam.comwri tes:
If I have a string say:

myvar[128] = "This is a string";

How do I use sprintf to convert the string so it has 4 spaces padded on
the left like:

" This is a string";
If you mean "in place" -- the result ending up in the same array -- then
you can't do it directly because sprintf is undefined if used with
overlapping objects.

Using memmove and memset is, IMO, the simplest way to do this.

--
Ben.
Jun 27 '08 #2
nospam <no@spam.comwro te:
If I have a string say:
myvar[128] = "This is a string";
I guess that's supposed to be

char myvar[128] = "This is a string";
How do I use sprintf to convert the string so it has 4 spaces padded on
the left like:
" This is a string";
sprint() doesn't convert strings, it prints into a string.
It looks as if you would like to use sprintf() with 'myvar'
as both the source and the destination and that's not pos-
sible. The C standard says about this specifically:

If copying takes place between objects that overlap,
the behavior is undefined.

which exactly addresses this situation. So there's no way
you can do this reliably with sprintf().

I guess in the end you want to do something more complicated
but for what you describe you want to do a simple

memmove( myvar + 4, myvar, strlen( myvar ) + 1 );
memset( myvar, ' ', 4 );

will do. Note the use of memmove() instead of memcpy() which
is required since source and destination overlap.

Regards, Jens
--
\ Jens Thoms Toerring ___ jt@toerring.de
\______________ ____________ http://toerring.de
Jun 27 '08 #3
On Mon, 09 Jun 2008 23:28:17 +0000, Jens Thoms Toerring wrote:
nospam <no@spam.comwro te:
>If I have a string say:
>myvar[128] = "This is a string";

I guess that's supposed to be

char myvar[128] = "This is a string";
>How do I use sprintf to convert the string so it has 4 spaces padded on
the left like:
>" This is a string";

sprint() doesn't convert strings, it prints into a string.
It looks as if you would like to use sprintf() with 'myvar'
as both the source and the destination and that's not pos-
sible. The C standard says about this specifically:

If copying takes place between objects that overlap,
the behavior is undefined.

which exactly addresses this situation. So there's no way
you can do this reliably with sprintf().

I guess in the end you want to do something more complicated
but for what you describe you want to do a simple

memmove( myvar + 4, myvar, strlen( myvar ) + 1 );
memset( myvar, ' ', 4 );

will do. Note the use of memmove() instead of memcpy() which
is required since source and destination overlap.

Regards, Jens

I need to use sprintf, similar to the legacy code I'm working with.
Something like this:

strncpy(fname,t mp+21,9); fname[9] = '\0';
strncpy(mname,t mp+31,1); mname[1] = '\0';

sprintf(tmp,"%4 s%-20s%-20s%-32s%-4s",
" ",fname,mname,l name," ");

Jun 27 '08 #4
On Tue, 10 Jun 2008 00:17:45 +0100, Ben Bacarisse wrote:
nospam <no@spam.comwri tes:
>If I have a string say:

myvar[128] = "This is a string";

How do I use sprintf to convert the string so it has 4 spaces padded on
the left like:

" This is a string";

If you mean "in place" -- the result ending up in the same array -- then
you can't do it directly because sprintf is undefined if used with
overlapping objects.

Using memmove and memset is, IMO, the simplest way to do this.


I need to use sprintf, similar to the legacy code I'm working with.
Something like this:

strncpy(fname,t mp+21,9); fname[9] = '\0';
strncpy(mname,t mp+31,1); mname[1] = '\0';

sprintf(tmp,"%4 s%-20s%-20s%-32s%-4s",
" ",fname,mname,l name," ");

Jun 27 '08 #5
nospam wrote:
>
If I have a string say:

myvar[128] = "This is a string";

How do I use sprintf to convert the string so it has 4 spaces
padded on the left like:

" This is a string";
For example, assuming you know s has space for the extra chars:

void sstretch(char *s, int amount) {
char *p1, *p2;

if (amount) {
pi = strchr(s, '\0');
if ((p1 s) && amount) {
p2 = p1 + amount;
do { /* move the string */
*p2-- = *p1--;
} while {p1 s);
}
while (amount) { /* inject the blanks */
*s++ = ' ';
amount--;
}
}
} /* untested */

--
[mail]: Chuck F (cbfalconer at maineline dot net)
[page]: <http://cbfalconer.home .att.net>
Try the download section.
** Posted from http://www.teranews.com **
Jun 27 '08 #6
nospam <no@spam.comwri tes:
On Tue, 10 Jun 2008 00:17:45 +0100, Ben Bacarisse wrote:
>nospam <no@spam.comwri tes:
>>If I have a string say:

myvar[128] = "This is a string";

How do I use sprintf to convert the string so it has 4 spaces padded on
the left like:

" This is a string";

If you mean "in place" -- the result ending up in the same array -- then
you can't do it directly because sprintf is undefined if used with
overlapping objects.

Using memmove and memset is, IMO, the simplest way to do this.

I need to use sprintf, similar to the legacy code I'm working with.
Something like this:
Why do you *need* to do it any particular way? I suspect we mean
different things by "need".
strncpy(fname,t mp+21,9); fname[9] = '\0';
strncpy(mname,t mp+31,1); mname[1] = '\0';

sprintf(tmp,"%4 s%-20s%-20s%-32s%-4s",
" ",fname,mname,l name," ");
If you *must* use sprintf, what would constitute use of sprintf?
Would this count?

memmove(myvar + 4, myvar, strlen(myvar) + 1);
sprintf(myvar, " ");
myvar[3] = ' ';

what about:

memmove(myvar + 4, myvar, strlen(myvar) + 1);
memset(myvar, ' ', 4);
sprintf(myvar + strlen(myvar), "");

?

All of this assumes that you need it done in-place. It is just
possible that what you are asking for is:

sprintf(tmp, " %s", myvar);

but that seems so obvious as to be an unlikely question.

--
Ben.
Jun 27 '08 #7
CBFalconer <cb********@yah oo.comwrites:
nospam wrote:
>>
If I have a string say:

myvar[128] = "This is a string";

How do I use sprintf to convert the string so it has 4 spaces
padded on the left like:

" This is a string";

For example, assuming you know s has space for the extra chars:

void sstretch(char *s, int amount) {
char *p1, *p2;

if (amount) {
pi = strchr(s, '\0');
if ((p1 s) && amount) {
p2 = p1 + amount;
do { /* move the string */
*p2-- = *p1--;
} while {p1 s);
}
while (amount) { /* inject the blanks */
*s++ = ' ';
amount--;
}
}
} /* untested */
Yuck. Two typos and two logic errors. You complain about not posting
corrections, so the correction is:

void sstretch(char *s, size_t amount)
{
memmove(s + amount, s, strlen(s) + 1);
memset(s, ' ', amount);
}

Why would you do all those gymnastics with the potential (so well
demonstrated) for errors?

--
Ben.
Jun 27 '08 #8
Ben Bacarisse <be********@bsb .me.ukwrites:
CBFalconer <cb********@yah oo.comwrites:
>nospam wrote:
>>>
If I have a string say:

myvar[128] = "This is a string";

How do I use sprintf to convert the string so it has 4 spaces
padded on the left like:

" This is a string";

For example, assuming you know s has space for the extra chars:

void sstretch(char *s, int amount) {
char *p1, *p2;

if (amount) {
pi = strchr(s, '\0');
if ((p1 s) && amount) {
p2 = p1 + amount;
do { /* move the string */
*p2-- = *p1--;
} while {p1 s);
}
while (amount) { /* inject the blanks */
*s++ = ' ';
amount--;
}
}
} /* untested */

Yuck. Two typos and two logic errors. You complain about not posting
corrections, so the correction is:

void sstretch(char *s, size_t amount)
{
memmove(s + amount, s, strlen(s) + 1);
memset(s, ' ', amount);
}

Why would you do all those gymnastics with the potential (so well
demonstrated) for errors?
I would also point out to the beginner, and "Chuck", to read the man
pages and to see why memmove is better than memcpy in this and other
situations. What the hell is that horrific mess above the correct
solution?!?!
Jun 27 '08 #9
On Jun 10, 7:57 am, Richard<rgr...@ gmail.comwrote:
Ben Bacarisse <ben.use...@bsb .me.ukwrites:
CBFalconer <cbfalco...@yah oo.comwrites:
nospam wrote:
>If I have a string say:
>myvar[128] = "This is a string";
>How do I use sprintf to convert the string so it has 4 spaces
padded on the left like:
>" This is a string";
For example, assuming you know s has space for the extra chars:
void sstretch(char *s, int amount) {
char *p1, *p2;
if (amount) {
pi = strchr(s, '\0');
if ((p1 s) && amount) {
p2 = p1 + amount;
do { /* move the string */
*p2-- = *p1--;
} while {p1 s);
}
while (amount) { /* inject the blanks */
*s++ = ' ';
amount--;
}
}
} /* untested */
Yuck. Two typos and two logic errors. You complain about not posting
corrections, so the correction is:
void sstretch(char *s, size_t amount)
{
memmove(s + amount, s, strlen(s) + 1);
memset(s, ' ', amount);
}
Why would you do all those gymnastics with the potential (so well
demonstrated) for errors?

I would also point out to the beginner, and "Chuck", to read the man
pages and to see why memmove is better than memcpy in this and other
situations. What the hell is that horrific mess above the correct
solution?!?!
Other than the overlapping memory case, how is memmove supposed to be
better than memcpy?
I am unaware of any other scenario in which memmove is better than
memcpy.
Jun 27 '08 #10

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

Similar topics

3
2060
by: Uttam | last post by:
Hello, Using ADO I have created a table and have also created fields. To create fields, I have used the following: ..Columns.Append "Field_Name", adWChar, 6 I load records into this created table including into this field.
4
2737
by: mhw | last post by:
I don't found function! Thanks£¡
1
4086
by: Anonieko Ramos | last post by:
> > > How to display multiple spaces in a dropdownlist webform1.aspx <asp:DropDownList id="DropDownList1" runat="server"></asp:DropDownList>
3
6099
by: Sam | last post by:
I want to divide character into 2 section. Example, 200412 divided into 2004 in A block and 12 in B block. Please advise how to use left(string, length) or right(string, length) for above request. Many thanks in advance.
3
15198
by: NathanC | last post by:
Left('ironman',4) Result - 'iron' Is there anyway to excute this task in VB.NET? Currently, I am determing the value of the 4th character, splitting on that, then grabbing the value of the first part of the split. It works, but is really cumbersome and doesn't account for a string with two consecutive values that are the same, but I might want to include both of them Example: ('neccesarry') Result: 'necce'
2
7242
by: Reny | last post by:
Hi, I came across a doubt on the String.PadLeft Method.The doubt is this -- What's difference it make if the argument to this function carries an integer whose value is less than the length of the string object For example in the sample code below(VB.NET) I could not see any difference
2
1946
by: akoymakoy | last post by:
is there a function to remove leading and trailing spaces on strings? example: word = " THE QUICK BROWN FOX " output: word = "THE QUICK BROWN FOX"
3
4010
by: AWW | last post by:
RichTextBox.Text = string & vbCR works but if I extract a substring with microsoft.visualbasic.left then vbCR stops working. I can do F5 executes with/without the Left and the vbCr does/doesNot work. Comment?
5
3772
by: =?Utf-8?B?Qm9iQWNoZ2lsbA==?= | last post by:
I need a function (or code) that will physically change the words in a text string to make the first word be last, second word next to last, etc. but maintain the same position of the letters in each word. e.g. Before: The dog ran After: ran dog the Is there such a thing?
3
15384
by: Elohim | last post by:
Hi to everybody, I'm a learner of C++. I'll really appreciate if you can help me or teach me something. Thank you in advance. #include<iostream> #include<string> int main() { std::cout << "Introduce your first name:";
0
10237
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10071
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...
0
9882
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8905
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
7431
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
5326
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5467
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3987
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2832
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.