473,773 Members | 2,269 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to truncate char string fromt beginning and replace chars instring by other chars in C or C++?

Hi,

I have a datetime char string returned from ctime_r, and it is in the
format like ""Wed Jun 30 21:49:08 1993\n\0", which has 26 chars
including the last terminate char '\0', and i would like to remove the
weekday information that is "Wed" here, and I also would like to
replace the spaces char by "_" and also remove the "\n" char. I didn't
know how to truncate the string from beginning or replace some chars
in a string with another chars without using a loop through one char
by one char of the string. I used the below code to achieve
replacement of " " by "_" and also removed the last "\n" char, without
considering removing the first 4 chars i.e. weekday information yet.
But even this I still didn't get what i like. Below is the code i
wrote:
#include <time.h>
#include <stdio.h>

int main(void)
{
time_t ltime;
char buf[50];

// Get the time
time(&ltime);

// The datetime string returned by ctime_r is in the format
// of "Wed Jun 30 21:49:08 1993\n\0"
printf("The time is: %s", ctime_r(&ltime, buf));

// replace the " " and ":" in the datetime string
// by "_"
buf[7] = "_"; // " ", line 18
buf[10] = "_"; // " ", line 19
buf[13] = "_"; // ":", line 20
buf[16] = "_"; // ":", line 21
buf[19] = "_"; // " ", line 22
buf[24] = "\0"; // remove the last \n char, line 23

// printf the new datetimestring
printf("The time is: %s", buf);

}

When I complied it with gcc, i got the below warning:

test_ctimer.c: In function `main':
test_ctimer.c:1 8: warning: assignment makes integer from pointer
without a cast
and same warning for line 19 to 23 too.

When I run it, I got:

The time is: Thu Aug 7 15:02:32 2008
The time is: Thu AugX 7X15X02X32X2008 Z

Can anyone kindly help me? I searched on the internet and it seems C
library doesn't have a function to truncate from the beginning? and it
also doesn't have a function for characher replacement. Should I have
to use a loop?

Thanks a lot for the help in advance.

Hongyu
Aug 7 '08 #1
13 3750
Hongyu wrote:
Hi,

I have a datetime char string returned from ctime_r, and it is in the
format like ""Wed Jun 30 21:49:08 1993\n\0", which has 26 chars
including the last terminate char '\0', and i would like to remove the
weekday information that is "Wed" here, and I also would like to
replace the spaces char by "_" and also remove the "\n" char. I didn't
know how to truncate the string from beginning or replace some chars
in a string with another chars without using a loop through one char
by one char of the string. I used the below code to achieve
replacement of " " by "_" and also removed the last "\n" char, without
considering removing the first 4 chars i.e. weekday information yet.
But even this I still didn't get what i like. Below is the code i
wrote:
#include <time.h>
#include <stdio.h>

int main(void)
{
time_t ltime;
char buf[50];

// Get the time
time(&ltime);

// The datetime string returned by ctime_r is in the format
// of "Wed Jun 30 21:49:08 1993\n\0"
printf("The time is: %s", ctime_r(&ltime, buf));

// replace the " " and ":" in the datetime string
// by "_"
buf[7] = "_"; // " ", line 18
For a single symbol you need to use single quotes:

buf[7] = '_';

(same everywhere).
buf[10] = "_"; // " ", line 19
buf[13] = "_"; // ":", line 20
buf[16] = "_"; // ":", line 21
buf[19] = "_"; // " ", line 22
buf[24] = "\0"; // remove the last \n char, line 23

// printf the new datetimestring
printf("The time is: %s", buf);

}
[..]
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 7 '08 #2
On Aug 7, 3:31*pm, Victor Bazarov <v.Abaza...@com Acast.netwrote:
Hongyu wrote:
Hi,
I have a datetime char string returned from ctime_r, *and it is in the
format like ""Wed Jun 30 21:49:08 1993\n\0", which has 26 chars
including the last terminate char '\0', and i would like to remove the
weekday information that is "Wed" here, and I also would like to
replace the spaces char by "_" and also remove the "\n" char. I didn't
know how to truncate the string from beginning *or replace some chars
in a string with another chars without using a loop through one char
by one char of the string. I used the below code to achieve
replacement of " " by "_" and also removed the last "\n" char, without
considering removing the first 4 chars i.e. weekday information yet.
But even this I still didn't get what i like. Below is the code i
wrote:
#include <time.h>
#include <stdio.h>
int main(void)
{
* *time_t ltime;
* *char buf[50];
* *// Get the time
* *time(&ltime);
* *// The datetime string returned by ctime_r is in the format
* *// of "Wed Jun 30 21:49:08 1993\n\0"
* *printf("The time is: %s", ctime_r(&ltime, buf));
* *// replace the " " and ":" in the datetime string
* *// by "_"
* *buf[7] = "_"; *// " ", line 18

For a single symbol you need to use single quotes:

* * *buf[7] = '_';

(same everywhere).
* *buf[10] = "_"; // " ", line 19
* *buf[13] = "_"; // ":", line 20
* *buf[16] = "_"; // ":", line 21
* *buf[19] = "_"; // " ", line 22
* *buf[24] = "\0"; // remove the last \n char, line 23
* *// printf the new datetimestring
* *printf("The time is: %s", buf);
}
[..]

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask- Hide quoted text -

- Show quoted text -
Thanks a lot for the prompty help, Victor. It worked! The compiler
errors disappered and the space was replaced by '-'. Can you also tell
me how to remove the chars in the beginning of the string? and how to
remove a char inside the string, because i have one more space inside
the string and would like to remove it. I tried to use like:
buf[0]='', but got compiler errors like: test_ctimer.c:1 8:12: empty
character constant

Thanks a lot.
Aug 7 '08 #3
Hongyu wrote:
[..] Can you also tell
me how to remove the chars in the beginning of the string? and how to
remove a char inside the string, because i have one more space inside
the string and would like to remove it. I tried to use like:
buf[0]='', but got compiler errors like: test_ctimer.c:1 8:12: empty
character constant
RTFM about 'memmove' function. It should work with overlapping ranges.
You can 'memmove' part of the string over itself, IIRC.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Aug 7 '08 #4
Hongyu wrote:

Thanks a lot for the prompty help, Victor. It worked! The compiler
errors disappered and the space was replaced by '-'. Can you also tell
me how to remove the chars in the beginning of the string? and how to
remove a char inside the string, because i have one more space inside
the string and would like to remove it. I tried to use like:
buf[0]='', but got compiler errors like: test_ctimer.c:1 8:12: empty
character constant
If you want to delete the contents and move the rest into place, you
either need to use memmove() or move the characters yourself.

See the example here:

http://www.cplusplus.com/reference/c...g/memmove.html
If you just want to overwrite them with spaces, you use ' '.


Brian
Aug 7 '08 #5
On Aug 7, 4:45*pm, "Default User" <defaultuse...@ yahoo.comwrote:
Hongyu wrote:
Thanks a lot for the prompty help, Victor. It worked! The compiler
errors disappered and the space was replaced by '-'. Can you also tell
me how to remove the chars in the beginning of the string? and how to
remove a char inside the string, because i have one more space inside
the string and would like to remove it. I tried to use like:
buf[0]='', but got compiler errors like: test_ctimer.c:1 8:12: empty
character constant

If you want to delete the contents and move the rest into place, you
either need to use memmove() or move the characters yourself.

See the example here:

http://www.cplusplus.com/reference/c...g/memmove.html

If you just want to overwrite them with spaces, you use ' '.

Brian
Thank you very much, Brian, "memmove can be very very useful", as the
link you provided mentioned, which is true. I will look at in more
detail and try it.
If you just want to overwrite them with spaces, you use ' '.
No, I would like to remove them. I will use memmove as you suggested.

Have a good rest of the day, everyone.
Aug 7 '08 #6
On Aug 7, 4:36*pm, Victor Bazarov <v.Abaza...@com Acast.netwrote:
Hongyu wrote:
[..] *Can you also tell
me how to remove the chars in the beginning of the string? and how to
remove a char inside the string, because i have one more space inside
the string and would like to remove it. I tried to use like:
buf[0]='', but got compiler errors like: test_ctimer.c:1 8:12: empty
character constant

RTFM about 'memmove' function. *It should work with overlapping ranges.
* You can 'memmove' part of the string over itself, IIRC.

V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Thank you very much for the help again, Victor. I will try it.
Aug 7 '08 #7
On 2008-08-07 16:56:42 -0400, Hongyu <ho*******@yaho o.comsaid:
>
No, I would like to remove them. I will use memmove as you suggested.
You don't need to move them at all. Just point to the first one you care about:

char text[] = "abcdefg";
char *last4 = text + 3;
std::cout << last4 << ;\n';

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Aug 7 '08 #8
On Aug 7, 5:20*pm, Pete Becker <p...@versatile coding.comwrote :
On 2008-08-07 16:56:42 -0400, Hongyu <hongyu...@yaho o.comsaid:
No, I would like to remove them. I will use memmove as you suggested.

You don't need to move them at all. Just point to the first one you care about:

char text[] = "abcdefg";
char *last4 = text + 3;
std::cout << last4 << ;\n';

--
* Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)
Thanks a lot, Pete. You are right, I see it works in the way you
shown. But since I am a entry level person, so I am not quite sure if
I will need to use the truncated string somewhere else, like use it as
an argument to invocate a function, or return this truncated string as
my void truncatedString (char * string) function, or char*
truncatedString (char* inputString) function so that it can be used
somewhere else, will it still work? Please forgive my silly questions.
Aug 7 '08 #9
On 2008-08-07 17:48:54 -0400, Hongyu <ho*******@yaho o.comsaid:
On Aug 7, 5:20Â*pm, Pete Becker <p...@versatile coding.comwrote :
>On 2008-08-07 16:56:42 -0400, Hongyu <hongyu...@yaho o.comsaid:
>>No, I would like to remove them. I will use memmove as you suggested.

You don't need to move them at all. Just point to the first one you care
about:
>>
char text[] = "abcdefg";
char *last4 = text + 3;
std::cout << last4 << ;\n';

--
Â* Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Thanks a lot, Pete. You are right, I see it works in the way you
shown. But since I am a entry level person, so I am not quite sure if
I will need to use the truncated string somewhere else, like use it as
an argument to invocate a function, or return this truncated string as
my void truncatedString (char * string) function, or char*
truncatedString (char* inputString) function so that it can be used
somewhere else, will it still work? Please forgive my silly questions.
Yes, it will work. A C-style string is just an array of char teminated
by a nul character. You can use a char* to point to the first character
that you're interested in: everything from that character out to the
nul character is still a char.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Aug 7 '08 #10

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

Similar topics

22
12761
by: Simon | last post by:
Hi, I have written a function to trim char *, but I have been told that my way could be dangerous and that I should use memmove(...) instead. but I am not sure why my code could be 'dangerous' or even why there could be a problem. here is the code ////////
5
17653
by: Roy Hills | last post by:
When I'm reading from or writing to a network socket, I want to use a struct to represent the structured data, but must use an unsigned char buffer for the call to sendto() or recvfrom(). I have two questions: 1. Is it generally safe to "overlay" the structure on the buffer, e.g.: unsigned char buffer;
11
24145
by: Walter Dnes (delete the 'z' to get my real address | last post by:
I've noticed a few threads (full of sound and fury, signifying nothing) here recently about allocation of large memory blocks. I'm about to start on a personal pet project where I'll be using memchr(), memcmp(), memmove() a lot. Is there an ANSI C maximium size for character arrays which are guaranteed to succeed, assuming the machine has sufficient memory? And will the memxxx() functions work with that size? I'm looking at hopefully...
5
3980
by: jab3 | last post by:
(again :)) Hello everyone. I'll ask this even at risk of being accused of not researching adequately. My question (before longer reasoning) is: How does declaring (or defining, whatever) a variable **var make it an array of pointers? I realize that 'char **var' is a pointer to a pointer of type char (I hope). And I realize that with var, var is actually a memory address (or at
5
3530
by: Jonas Åkermark | last post by:
Hello! I have a problem decoding the czech character: r The HTML code for this character is ř but when running Server.HTMLdecode on that string it just returns ř instead of the real char. (It works on a lot of other characters) I need to decode this string in order to render an image with this character as a part of a headline.
7
3256
by: GysAnn | last post by:
Hello, I'm looking for a function for converting the input to a regular text. Example: when the input is "aBCdefgHI jkLM ooPP" the return value of the function should be "Abcdefghi Jklm Oopp" Thanks in advance, Anita
6
1308
by: Chris Dunaway | last post by:
I am using a StringBuilder like this: Dim sb As New StringBuilder sb.Append("Text field 1: {TXT1}" & VbCrLf) sb.Append("Text field 2: {TXT2}" & VbCrLf) sb.Append("Text field 3: {TXT3}" & VbCrLf) And then later in the code I use this:
8
7741
by: electrixnow | last post by:
I am reading in a comma delimited text file, with a document #,revision letter on each line. example: 123,A 456,B There are 19000 lines to this master document file. I will also be reading in a file that has about 200 lines that has the same structure as the first file. I need to compare File A and B and produce File C.
10
2541
by: tommaso.gastaldi | last post by:
I am extracting some field names from a table of a db (it's an OledbSchemaguid table). It occurs for some OleDbSchema driver that NameDBField = cstr(DataRow.Item(3)) return a string that is composed by the characters of the field name, for instance MYFIELD plus 1 Nothing. I know that the Nothing is there because, since I was having a lot of problem with these strange strings
0
9621
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...
0
9454
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
10264
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
10106
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
9914
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...
1
7463
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
6717
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();...
1
4012
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
2852
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.