how to delete a character from a string

  • (2 Pages)
  • +
  • 1
  • 2

28 Replies - 85757 Views - Last Post: 15 January 2009 - 10:30 AM Rate Topic: -----

#16 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3105
  • View blog
  • Posts: 19,144
  • Joined: 14-September 07

Re: how to delete a character from a string

Posted 14 January 2009 - 02:03 PM

Example:

first string: |S|t|r|i|n|g|\0|, it is declared in memory on the stack
Remove i, shift left: |S|t|r|n|g|\0| |<- empty "space" after the null terminator, the C string still holds the same amount of memory

Unaccessable unless you declare that slot explicitly. It's technically not a memory leak at this point since a.) you can access it and b.) the stack will get cleared after program/method execution.

edit: In hindsight the program will not overwrite bounds since it thinks that Strng\0 has the same space as String\0. Anyways...


edited for a better diagram

This post has been edited by KYA: 14 January 2009 - 02:09 PM

Was This Post Helpful? 0
  • +
  • -

#17 matthew180  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 51
  • View blog
  • Posts: 202
  • Joined: 07-January 09

Re: how to delete a character from a string

Posted 14 January 2009 - 02:36 PM

Inaccessible?

There is only one way to get that variable on the stack:

char string[20];

If you allocate dynamically the memory will be taken from the heap, or where ever the OS decides:

char *string;

string = malloc(20);



In either case, you know the length of your local buffer, or you know how much memory you requested via malloc(). In the case of malloc(), the OS also knows how big the chunk of memory is and will release it when you call free() with the address malloc() gave you.

In the first case, where you just define a local char array, the bytes in that array have *nothing* to do with the size of the array. In fact, the bytes will be full of junk (whatever values happened to be at those memory addresses on the stack when the function was called) until you write something meaningful into them.

Just because a zero value (a.k.a. NULL) is written to one of those bytes does not make the rest of the bytes in the array inaccessible. The "empty space" you refer to is not a leak or unaccounted for, it is still part of the char array as defined, and still perfectly usable:

char buf[20];  // 20 bytes of junk when the function is called

// After strcpy is done, the last 7 bytes in buf will still be junk, but
// still perfectly accessible.
strcpy(buf, "Hello World!");

// Get rid of the '!'
delete_char(buf, '!', 0);

// Add back the '!'
strcat(buf, "!");



Matthew

This post has been edited by matthew180: 14 January 2009 - 02:37 PM

Was This Post Helpful? 0
  • +
  • -

#18 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3105
  • View blog
  • Posts: 19,144
  • Joined: 14-September 07

Re: how to delete a character from a string

Posted 14 January 2009 - 03:59 PM

Yes. But it is bad practice. Let's say we strcpy it to an allocated segment of memory. Are you hard coding/remembering how many "empty" segment you have after the null terminator? You're effectively circumventing the whole point of why C has a null terminator.

Quote

Inaccessible?


Only accessible through the exact index, like you mentioned. So everything from then on would have to be hard coded since you wouldn't know which strings were using null terminators as they are intended and which ones have random bits of trailing nothingness.

Again, not a problem if you're the only programmer working on this file in a program only you will ever maintain.
Was This Post Helpful? 0
  • +
  • -

#19 matthew180  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 51
  • View blog
  • Posts: 202
  • Joined: 07-January 09

Re: how to delete a character from a string

Posted 14 January 2009 - 04:34 PM

View PostKYA, on 14 Jan, 2009 - 02:59 PM, said:

Yes. But it is bad practice. Let's say we strcpy it to an allocated segment of memory. Are you hard coding/remembering how many "empty" segment you have after the null terminator? You're effectively circumventing the whole point of why C has a null terminator.


Bad practice? To know how big your arrays are? Absolutely you better be keeping track of how big your arrays are! If you have no idea how big your buffer is, what is going to keep you from overflowing? I'm not circumventing anything.

I suppose you would think this is okay?

char buf1[10];
char buf2[5];

strcpy(buf1, "This is a test");
strcpy(buf2, buf1);




And you are also saying that this is bad practice?

char name[10];

strcpy(name, "Jon Doe");
printf("%s\n", name);

strcpy(name, "Jane Dane");
printf("%s\n", name);

strcpy(name, "Al");
printf("%s", name);




View PostKYA, on 14 Jan, 2009 - 02:59 PM, said:

Only accessible through the exact index, like you mentioned. So everything from then on would have to be hard coded since you wouldn't know which strings were using null terminators as they are intended and which ones have random bits of trailing nothingness.

Again, not a problem if you're the only programmer working on this file in a program only you will ever maintain.


Huh?

When looking for the "NULL", the string functions start at the left and stop at the first NULL they come to. It does not matter what the data is after the NULL. If you extend the "string" then the NULL is moved further to the right. If you shorten the "string" by copying new data into it, or simply moving the NULL, then so be it, you now have a shorter "string". But none of that has anything to do with the size of your allocated array of bytes to hold the data being called a "string".

How about the strncpy() circumstance where the source is longer than the destination buffer? From the man page itself:

The strncpy() function copies at most len characters from src into dst.
If src is less than len characters long, the remainder of dst is filled
with `\0' characters. Otherwise, dst is not terminated.


Hmm, not terminated... One of the standard "string" functions actually does not terminate... Funny, an unterminated string, must be bad practice. Let's see who wrote that function spec anyway:

STANDARDS
The strcpy() and strncpy() functions conform to ISO/IEC 9899:1990
(``ISO C90''). The stpcpy() function is an MS-DOS and GNUism. The
stpcpy() function conforms to no standard.



Matthew
Was This Post Helpful? 0
  • +
  • -

#20 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3105
  • View blog
  • Posts: 19,144
  • Joined: 14-September 07

Re: how to delete a character from a string

Posted 14 January 2009 - 05:05 PM

You are reading what I'm saying incorrectly.

I'm not saying ignore how big your arrays are. I'm saying shifting everything left and leaving blank spaces AFTER the null terminator is bad. The buffer has nothing to do with what I'm saying.


Why are you lecturing me on strcpy? You didn't even use it in your example aside from putting some macros into your char arrays. Plus now that i look at it again, you wasted a LOT of memory. A KB of memory per char array??? Why?

STRING\0
STRNG\0' '
SRNG\0' '' '
SNG\0' '' '' '
SG\0' '' '' '' '
G\0' '' '' '' '' '

I'm not attacking you, I was just trying to illustrate why doing the above may turn out to be a bad idea in the long run.

edited for a typo

This post has been edited by KYA: 14 January 2009 - 05:11 PM

Was This Post Helpful? 0
  • +
  • -

#21 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: how to delete a character from a string

Posted 14 January 2009 - 05:27 PM

Could we draw this to a close for now ... at least until the OP let's us know more?

Since the OP stressed he was a beginner, it would seem likely that NO dynamic memory ... and NOT much memory was involved ...

But ... the OP may surprise us yet... And then we may lean towards dynamic memory byte pinching :D

Shalom,
David
http://developers-he.../index.p...opic,106.0.html
http://developers-he...index.php/topic,46.0.html

P.S.

I hope we all have learned at least a little from all this :)
Was This Post Helpful? 0
  • +
  • -

#22 matthew180  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 51
  • View blog
  • Posts: 202
  • Joined: 07-January 09

Re: how to delete a character from a string

Posted 14 January 2009 - 09:11 PM

View PostKYA, on 14 Jan, 2009 - 04:05 PM, said:

You are reading what I'm saying incorrectly.

I'm not saying ignore how big your arrays are. I'm saying shifting everything left and leaving blank spaces AFTER the null terminator is bad. The buffer has nothing to do with what I'm saying.


Why? What does it matter what comes after the NULL indicator? As long as you don't write past the bounds of your array, it makes no difference. What you care about is the data before the NULL, not what comes after. In a C "string", what comes after the NULL absolutely does not matter.

For the record, my code does not do *anything* with the data past the NULL, I don't waste time setting the bytes to "blank" or "space" or anything else, there is simply no point. I also do not change the size of the array and I make every attempt possible to prevent a buffer overflow.

View PostKYA, on 14 Jan, 2009 - 04:05 PM, said:

Why are you lecturing me on strcpy? You didn't even use it in your example aside from putting some macros into your char arrays. Plus now that i look at it again, you wasted a LOT of memory. A KB of memory per char array??? Why?


I'm talking about strcpy because what my delete_char function does is *exactly* the same result you will find if you used strcpy with the result string (shown below):

int i;
char buf1[20];
char buf2[20];

strcpy(buf1, "Hello World!");
strcpy(buf2, "Hello World!");

delete_char(buf1, 'l', 0);
strcpy(buf2, "Heo Word!");

for ( i = 0; i < 20; i++ )
	printf("%c[%02X] ", buf1[i], buf1[i]);

printf("\n");

for ( i = 0; i < 20; i++ )
	printf("%c[%02X] ", buf2[i], buf2[i]);

printf("\n");



I think you will find that the data in both buffers is exactly the same to the point of the original "Hello World!" string (including the original NULL still sitting there). So if that is how the C string functions work, why is it bad for my code to work in a similar way?

As for the example buffers in my test code, the 1024 length was arbitrary, it could have been anything and would totally depend on the requirements of the application.

View PostKYA, on 14 Jan, 2009 - 04:05 PM, said:

I'm not attacking you, I was just trying to illustrate why doing the above may turn out to be a bad idea in the long run.


Hmm, I seem to recall at least three direct comments that claim my code might be dangerous, confusing, bad practice, and that what I write would not work in a multi-developer project:

View PostKYA, on 14 Jan, 2009 - 04:05 PM, said:

1. I see where you're coming from, but in your example, if enough items are done in that manner you'll corrupt the stack.
2. Yes. But it is bad practice.
3. Again, not a problem if you're the only programmer working on this file in a program only you will ever maintain.


If that is not an attack, then it certainly comes close. #1 is false. #2 and #3 you might as well just claim I can't code...


David W and Original Poster: Sorry for all the trouble, it seems I wrecked this thread.

Matthew
Was This Post Helpful? 0
  • +
  • -

#23 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3105
  • View blog
  • Posts: 19,144
  • Joined: 14-September 07

Re: how to delete a character from a string

Posted 14 January 2009 - 10:33 PM

I didn't say that.

Quote

For the record, my code does not do *anything* with the data past the NULL, I don't waste time setting the bytes to "blank" or "space" or anything else, there is simply no point. I also do not change the size of the array and I make every attempt possible to prevent a buffer overflow.


If there's no point for them to be there why have them at all? Why don't we allocate a new array after the removal of an item and proceed in that manner?

The stack is corrupted in so far as those extra slots contain garbage.

I am not saying you can't code. I was merely pointing out an alternative and why the provided solution(s) may want to go in another path

This post has been edited by KYA: 14 January 2009 - 10:42 PM

Was This Post Helpful? 0
  • +
  • -

#24 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: how to delete a character from a string

Posted 15 January 2009 - 12:47 AM

Matthew, I think you have fairly defended yourself and that your last simple example was excellent, and KYA's arguments against it hold NO water at all, since ...

Once one declares a C string like ...

char testStr[] = "some string"; /* test string for 'i' removal */

it is NOT possible to change the size of memory of THAT string AFTER the program is compiled, and this should be obvious to KYA and to all.

Again ... KYA's advanced method, using an iterator, is most probably NOT what a professed 'just beginner' was wanting ... (however it will be excellent for the OP's future reference if and when the OP advances and will certainly be more relevant if the OP is wanting a C++ solution instead of a C type solution ... a C type string is still what many beginners in C++ start out with.)

And again ALSO, a professed 'just beginner' is NOT likely to be using dynamic memory.

Recall the OP's words ... "the simplest way iam just a biggner" ...

"... example: if i want to delete "i" from vishnu what should i do? Please give me the simplest way iam just a biggner.if possible please give me a sample code "

Shalom,
David
http://developers-he.../index.p...opic,106.0.html
http://developers-he...index.php/topic,46.0.html

This post has been edited by David W: 15 January 2009 - 01:04 AM

Was This Post Helpful? 0
  • +
  • -

#25 Linkowiezi  Icon User is offline

  • D.I.C Regular

Reputation: 58
  • View blog
  • Posts: 316
  • Joined: 07-October 08

Re: how to delete a character from a string

Posted 15 January 2009 - 02:26 AM

I agree with DavidW, and I think that the two of you(KYA & matthew180) should stop flooding the OP's thread with unnecessairily much information for the OP to read trough and probably just get confused about since stated in the first post that the OP actually is a beginner and want help getting started not scared away by confusion and harsh words tossed to the left and right.

Sorry for the long sentence, hope none suffocated trying to read that out loud in one breath :P
Was This Post Helpful? 0
  • +
  • -

#26 achal3754  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 26
  • Joined: 14-January 09

Re: how to delete a character from a string

Posted 15 January 2009 - 02:58 AM

  Use following logic
suppose name  is the string whose character you want to delete
and chToBeDeleted is the character you want to delete. then 

#include<iostream.h>
#include <string.h>
int main()
{
   char name[10];
   char chToBeDeleted;
  cin>>name;
 cin>>chToBeDeleted;
cout<<"name = "<<name<<endl;
cout<<"chToBeDeleted = "<<chToBeDeleted<<"\n";
int strLen =strlen(name);
 for(int i=0;i<strLen;i++)
{
   if(chToBeDeleted == name[i])
   {
	  for(int j=i;j<(strLen -1);j++)
			  name[j]=name[j+1];
	 strLen--;
	  name[strLen]='\0';
   }
}
cout<<"name = "<<name<<endl;
cout<<"chToBeDeleted = "<<chToBeDeleted<<"\n";


	return 0;
}


View Postvishnu213, on 14 Jan, 2009 - 06:49 AM, said:

Hai friends, iam stuck with a topic while iam dong my mini project .I just want to delete a character from a sting
example: if i want to delete "i" from vishnu what should i do? Please give me the simplest way iam just a biggner.if possible please give me a sample code

Was This Post Helpful? 0
  • +
  • -

#27 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: how to delete a character from a string

Posted 15 January 2009 - 06:11 AM

Quote

achal3754


Did you try your code with input strings like 'aasiiiccc' to see if, for example, it removes all the 'i's ?

See these modifications, using Matt's pointer example, to remove ALL occurrences of the 'char' that you desire to remove in a C string ...

Note that #include <iostream.h> is no longer in vogue unless you have a really old C++ compiler ... (There are many free C++ compilers available at present.)

#include <iostream> // old was <iostream.h>
#include <string.h> // for strlen(...) for Cstrings
using namespace std;

int main()
{
    char testStr[10]; // to hold a maximum of 9 characters + the termianl '\0' char
    char chToBeDeleted;
    char *pTestStr = testStr; // pointer to C string to hold address of 'testStr'
    
    cout << "Enter a testStr like 'ababbabbb' (up to 9 char's maximum): ";
    cin >> testStr;
    
    cout << "Enter a char to be deleted: ";
    cin >> chToBeDeleted;

    cout << "Before deletions testStr = " << testStr 
         << " Number of characters = " << strlen(testStr) << endl;
    for(int i=0; testStr[i]!=0; i++)
        if(testStr[i] != chToBeDeleted)
            *pTestStr++ = testStr[i]; // copy only desired char's as per Matt
            // Note: the pointer above only advances for the desired char's
            
    *pTestStr = 0; // null terminate new end of the desired C string
    
    cout << "After deletions testStr  = " << testStr
         << " Number of characters = " << strlen(testStr) << endl
         << "Press 'Enter' to continue ... " << flush;
    
    cin.sync(); // to flush cin stream ...
    cin.get();  // to keep window open for 'Enter' key to be pressed
}

This post has been edited by David W: 15 January 2009 - 06:52 AM

Was This Post Helpful? 0
  • +
  • -

#28 KYA  Icon User is offline

  • g++ jameson.cpp -o beverage
  • member icon

Reputation: 3105
  • View blog
  • Posts: 19,144
  • Joined: 14-September 07

Re: how to delete a character from a string

Posted 15 January 2009 - 09:02 AM

Quote

Once one declares a C string like ...

char testStr[] = "some string"; /* test string for 'i' removal */

it is NOT possible to change the size of memory of THAT string AFTER the program is compiled, and this should be obvious to KYA and to all.


I was not suggesting that the amount of memory dedicated to the string on to the stack could be changed. I was meekly, even humbly pointing out that having all that trailing nothingness is not good.

What you can do is: iterate through to the string to find a null terminator, allocate new memory to fit the size of what you just found and strcpy.

I'm not sure if any of you come from a java background, but being apathetic about an issue like that gives that impression. "We don't need to worry about it because the stack will clear itself" mentality. Maybe I'm the only one who cares about minute things like that and again I APOLOGIZE a thousands times over for ever bringing it up. edit: I should have said overflow the stack rather then corrupt although, in my mind, having all those unused garbage values is corruption.

But hey I must not know what the hell I'm talking about. I'll just keep information to myself from now on.

This post has been edited by KYA: 15 January 2009 - 09:24 AM

Was This Post Helpful? 0
  • +
  • -

#29 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: how to delete a character from a string

Posted 15 January 2009 - 10:30 AM

Quote

... I'll just keep information to myself from now on.


Please don't do that ... Your contributions are very valuable ... But we might, anyone of us, get a little extreme at times ... as you pointed out to me in the past ...and I appreciated that. ... We do need each others encouragement and (fairly) free comments ... to keep some sort of balance ... n'est pas? :)

Shalom,
David

P.S. I appreciated your example with iterators ... but my point was that the OP ... (OP where are you?) ... might not, being, as the OP stated, 'just a beginner'.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2