473,785 Members | 2,255 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
41 12467
Richard<rg****@ gmail.comwrites :
Ben Bacarisse <be********@bsb .me.ukwrites:
<snip>
>void sstretch(char *s, size_t amount)
{
memmove(s + amount, s, strlen(s) + 1);
memset(s, ' ', amount);
}

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.
That is an odd way of putting it. memmove is *essential* in this
situation. In other situations memcpy may be better. I did not
explain because someone else has already done so.

--
Ben.
Jun 27 '08 #11
Ben Bacarisse <be********@bsb .me.ukwrites:
Richard<rg****@ gmail.comwrites :
>Ben Bacarisse <be********@bsb .me.ukwrites:
<snip>
>>void sstretch(char *s, size_t amount)
{
memmove(s + amount, s, strlen(s) + 1);
memset(s, ' ', amount);
}

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.

That is an odd way of putting it. memmove is *essential* in this
situation. In other situations memcpy may be better. I did not
explain because someone else has already done so.
I didnt see any other post on the matter. "better" is mentioned to get
people to read the man pages. Self help and all that. I see nothing odd
at all in mentioning it as "better".
Jun 27 '08 #12
Richard<rg****@ gmail.comwrites :
Ben Bacarisse <be********@bsb .me.ukwrites:
>Richard<rg**** @gmail.comwrite s:
>>Ben Bacarisse <be********@bsb .me.ukwrites:
<snip>
>>>void sstretch(char *s, size_t amount)
{
memmove(s + amount, s, strlen(s) + 1);
memset(s, ' ', amount);
}
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.

That is an odd way of putting it. memmove is *essential* in this
situation. In other situations memcpy may be better. I did not
explain because someone else has already done so.

I didnt see any other post on the matter.
Message ID: <6b************ *@mid.uni-berlin.de Jens Thoms Toerring:

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

--
Ben.
Jun 27 '08 #13
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";

/* BEGIN new.c */

#include <stdio.h>

int main(void)
{
char myvar[128] = "This is a string";

sprintf(myvar, "%20s", "This is a string");
puts(myvar);
return 0;
}

/* END new.c */

--
pete
Jun 27 '08 #14
Ben Bacarisse wrote:
CBFalconer <cb********@yah oo.comwrites:
.... snip ...
>
> 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);
}
One does it for the exercise. I see only one typo [while {p1 >
s)]] and one unnecessary test [&& amount]. A compilation may well
show up more. What did you see?

Incidentally, a speed comparison would be interesting. I don't
think your version allows for amount == 0 and for an empty original
string. I would have to check the specs for memove and memset with
care.

--
[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 #15
Ben Bacarisse wrote:
Richard<rg****@ gmail.comwrites :
>Ben Bacarisse <be********@bsb .me.ukwrites:
<snip>
>>void sstretch(char *s, size_t amount)
{
memmove(s + amount, s, strlen(s) + 1);
memset(s, ' ', amount);
}

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.

That is an odd way of putting it. memmove is *essential* in this
situation. In other situations memcpy may be better. I did not
explain because someone else has already done so.
Richard is a troll. I didn't use memmove, but did the move coding
directly.

--
[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 #16
Ben Bacarisse said:
Richard<rg****@ gmail.comwrites :
>Ben Bacarisse <be********@bsb .me.ukwrites:
<snip>
>>void sstretch(char *s, size_t amount)
{
memmove(s + amount, s, strlen(s) + 1);
memset(s, ' ', amount);
}

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.

That is an odd way of putting it. memmove is *essential* in this
situation.
Um, no, it isn't. You /can/ bully the bytes around by hand if you prefer
(but if you do so, you need to push them *just so*, or they'll turn on
you). If you just meant that memcpy is a non-starter here, then of course
I agree.

--
Richard Heathfield <http://www.cpax.org.uk >
Email: -http://www. +rjh@
Google users: <http://www.cpax.org.uk/prg/writings/googly.php>
"Usenet is a strange place" - dmr 29 July 1999
Jun 27 '08 #17
rio

"nospam" <no@spam.comh a scritto nel messaggio
news:co******** *************** *******@comcast .com...
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!
it not use sprint not tested

/* return the string if ok
0 if error
using like:
char *pc;
char *s="This is a string"

if((pc=the4spac es(s))==0) Error();
use(pc);
....
free(pc);
*/
char* the4spaces(char * s)
{char *p1, *p2, p;
unsigned c, sz;
/*************** *****/
if(s==0) return 0;
if( (int) (sz=strlen(s)) < 0) return 0;
p=p2=malloc(sz+ 8);
if(p2==0) return 0;
p1=s;
while( *p1 && (*p1==' '||*p1=='\t')) ++p1;
*p2++=' '; *p2++=' '; *p2++=' '; *p2++=' ';
while(*p2++=*p1 ++);
return p;
}

Jun 27 '08 #18
rio

"rio" <a@b.cha scritto nel messaggio
news:48******** *************** @reader5.news.t in.it...
>
"rio" <a@b.cha scritto nel messaggio news:484e3100$0 $18150/*
> one better version?
d should be mallocched or 0
e.g.
char *d=0;
unsigned sz=0;
----
if((sz=the4spac es(&d, sz, string))==0) error();
free(*d);
----------
*/

unsigned the4spaces(char ** d, unsigned sz, char* s)
{char *p1, *p2, p;
unsigned c, sz, r;
/*************** *****/
if(s==0) goto l0;
if( (int) (c=strlen(s)) < 0)
goto l0;
r=sz;
p=*d;
> if(c+4+1<sz)
{if( p=realloc(*d, c+8)==0)
arrrrrrrrrrrrrh hgjgjg ^^^^^^^^^^^^^^
if( (p=realloc(*d, c+8))==0)
> {l0:;
free(*d); *d=0; return 0;
}
r=c+8;
*d=p
> }
p1=s; p2=p; *d=p;
^^^^^^^not
p1=s; p2=p;
>while( *p1 && (*p1==' '||*p1=='\t')) ++p1;
*p2++=' '; *p2++=' '; *p2++=' '; *p2++=' ';
while(*p2++=*p 1++);
return r;
}
this seems good
not know if compile

Jun 27 '08 #19
rio

"CBFalconer " <cb********@yah oo.comha scritto nel messaggio
news:48******** *******@yahoo.c om...
Ben Bacarisse wrote:
>CBFalconer <cb********@yah oo.comwrites:
... snip ...
>>
>> 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);
}

One does it for the exercise. I see only one typo [while {p1 >
s)]] and one unnecessary test [&& amount]. A compilation may well
show up more. What did you see?
>> pi = strchr(s, '\0');
seems an error; should be p1= strchr(s, '\0');?
Incidentally, a speed comparison would be interesting. I don't
think your version allows for amount == 0 and for an empty original
string. I would have to check the specs for memove and memset with
care.

--
[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 #20

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

Similar topics

3
2061
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
2738
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
6100
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
15200
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
1947
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
9645
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
10095
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
9954
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
8979
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
7502
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
6741
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
5383
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...
1
4054
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
2881
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.