Re: shorten string length by 1
- From: Joe Wright <joewwright@xxxxxxxxxxx>
- Date: Fri, 15 Apr 2005 15:49:26 -0400
John Smith wrote:
Jason wrote:
John Smith wrote:
I want to shorten a string by replacing the last character by '\0'.
The following code displays the string. It works fine. It's in a loop and different strings are displayed without problems. ----------------------------------------------------------- temp= strlen(aGroup); for (i=0; i< temp;i++) printf(" %d %d %c\n", i+1,temp,aGroup[i]); ---------------------------------------------------------
To replace the last character by '\0', I have tried
aGroup[i-1]='\0';
or temp--; aGroup[temp]='\0';
or aGroup[temp-1]='\0';
Though there is no compiling error, the program crashed when ran (I was asked whether to send error report to Microsoft. Same error for all three.)
But "aGroup[22]='\0';" works (I knew the length is greater than 22.)
What gives? This is on VC++ 6.0.
Verify that aGroup has been properly declared, and that it is suffiently large enough to store the string you are copying into it. Perhaps you are overflowing a buffer, or forgot to properly call malloc?
-Jason -Jason
Thanks for the reply.
As I said. The program worked fine until I added the code (any one of the three) to replace the last character. I think this should rule out the potential problems you mentioned.
BTW, aGroup is declared as "char aGroup[2048];" which is probably 10 times larger than what it can be.
#include <stdio.h> #include <string.h>
int main(void)
{
char aGroup[2048];
int i;
strcpy(aGroup, "Hello Sailor");
i = strlen(aGroup);
while (i--) {
puts(aGroup);
aGroup[i] = '\0';
}
return 0;
}Why is this thread so long? -- Joe Wright mailto:joewwright@xxxxxxxxxxx "Everything should be made as simple as possible, but not simpler." --- Albert Einstein --- .
- Follow-Ups:
- Re: shorten string length by 1
- From: Mac
- Re: shorten string length by 1
- References:
- shorten string length by 1
- From: John Smith
- Re: shorten string length by 1
- From: Jason
- Re: shorten string length by 1
- From: John Smith
- shorten string length by 1
- Prev by Date: Re: char to vector problem
- Next by Date: Re: Convert float to string without trailing 0s
- Previous by thread: Re: shorten string length by 1
- Next by thread: Re: shorten string length by 1
- Index(es):
Relevant Pages
|