how to delete a character from a string

  • (2 Pages)
  • +
  • 1
  • 2

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

#1 vishnu213  Icon User is offline

  • New D.I.C Head

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

how to delete a character from a string

Post icon  Posted 14 January 2009 - 07:49 AM

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
Is This A Good Question/Topic? 0
  • +

Replies To: how to delete a character from a string

#2 KYA  Icon User is offline

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

Reputation: 3120
  • View blog
  • Posts: 19,163
  • Joined: 14-September 07

Re: how to delete a character from a string

Posted 14 January 2009 - 08:20 AM

You'll need to set an itertor to the string and give the iterator the location what what you want to remove/delete:

#include <iostream>
#include <string>
using namespace std;

int main ()
{
  string str ("This is an example phrase.");
  string::iterator it;

  // erase used in the same order as described above:
  str.erase (10,8);
  cout << str << endl;		// "This is an phrase."

  it=str.begin()+9;
  str.erase (it);
  cout << str << endl;		// "This is a phrase."

  str.erase (str.begin()+5, str.end()-7);
  cout << str << endl;		// "This phrase."
  return 0;
}



Full write up HERE
Was This Post Helpful? 0
  • +
  • -

#3 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 - 09:38 AM

Or ... a C way to do it ... see below:
(But see Matt's better sol'n, in post 11 below, using a pointer)

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


#include <stdio.h>

/* forward declaration / prototype */
void removeAll( char s[], char x );

int main ()
{
    char s[] = "iiinnviiishnnnnuiii"; /* "i" from vishnu */
    printf( "Before 'i's removed: '%s'\n", s );
    
    int i, j;
    for( i=0; s[i]!=0; ++i )
    {
        while(s[i]=='i') /* copy all chars, including NULL at end, over char to left */
        {
            j=i;
            while(s[j]!=0)
            {
                s[j]=s[j+1];
                ++j;
            }
        }
    }
    printf( "After 'i's removed: '%s'\n", s );
    
    removeAll( s, 'n' );
    printf( "After 'n's removed: '%s'\n", s );
    

    getchar();
    return 0;
}

/* removes all char = x in the C string s */
/* recall C strings have a '\0' to terminate the string */
void removeAll( char s[], char x )
{
    int i, j;
    for( i=0; s[i]!=0; ++i )
    {
        while(s[i]==x) /* copy all chars, including NULL at end, over char to left */
        {
            j=i;
            while(s[j]!=0)
            {
                s[j]=s[j+1];
                ++j;
            }
        }
    }   
}

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

Was This Post Helpful? 0
  • +
  • -

#4 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 - 10:12 AM

Similar to what David W wrote.

Matthew

#include <stdio.h>
#include <string.h>		// strncpy


#define MAX_STRING 1024
#define STR1 "Thisx isx ax testx"
#define STR2 "Hello xWorld!"


void delete_at(char *src, int pos, int len);
void delete_char(char *src, char c, int len);


int
main(void)
{
	char buf1[MAX_STRING];
	char buf2[MAX_STRING];

	strncpy(buf1, STR1, sizeof(buf1));
	strncpy(buf2, STR2, sizeof(buf2));

	printf("\n");

	printf("Delete all 'x' characters from: [%s] -> ", buf1);
	delete_char(buf1, 'x', 0);
	printf("[%s]\n\n", buf1);

	printf("Delete the character at position 6 (zero offset) from: [%s] -> ", buf2);
	delete_at(buf2, 6, 0);
	printf("[%s]\n\n", buf2);

	return 0;
}
// main()


/**
 * Delete a character from the specified position (zero offset)
 *
 * The len parameter allows the function to work with non null terminated
 * strings and could also be considered a weak attempt at buffer overflow
 * protection.
 *
 * @note The original string is modified.
 *
 * @param[in] src   Pointer to string from which to remove the character
 * @param[in] pos   Zero-offset position of the character to remove
 * @param[in] len   Max number of characters to process
 */
void
delete_at(char *src, int pos, int len)
{
	char *dst;
	int i;

	if ( pos < 0 )
		return;

	// Small attempt to control a buffer overflow if the
	// the string is not null-terminated and a proper length
	// is not specified.
	if ( len <= 0 )
		len = MAX_STRING;

	if ( pos >= len )
		return;

	src += pos;
	dst = src;
	src++;

	for ( i = pos + 1; i < len && *src != 0; i++ )
		*dst++ = *src++;

	// Ensure the string is null-terminated.
	*dst = 0;

	return;
}
// delete_at()


/**
 * Delete all occurrences of a character from a string
 *
 * The len parameter allows the function to work with non null terminated
 * strings and could also be considered a weak attempt at buffer overflow
 * protection.
 *
 * @note The original string is modified.
 *
 * @param[in] src   Pointer to string from which to remove characters
 * @param[in] c	 Character to remove
 * @param[in] len   Max number of characters to process
 */
void
delete_char(char *src, char c, int len)
{
	char *dst;
	int i;

	// Do not remove NULL characters.
	if ( c == 0 )
		return;

	// Small attempt to control a buffer overflow if the
	// the string is not null-terminated and a proper length
	// is not specified.
	if ( len <= 0 )
		len = MAX_STRING;

	dst = src;

	for ( i = 0; i < len && *src != 0; i++, src++ )
	{
		if ( *src != c )
			*dst++ = *src;
	}

	// Ensure the string is null-terminated.
	*dst = 0;

	return;
}
// delete_char()


Was This Post Helpful? 0
  • +
  • -

#5 KYA  Icon User is offline

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

Reputation: 3120
  • View blog
  • Posts: 19,163
  • Joined: 14-September 07

Re: how to delete a character from a string

Posted 14 January 2009 - 10:58 AM

As long as the OP knows once an array size is declared you cannot "erase" an index in the middle. Your code examples (both of you) are misleading. You can make that slot blank for example, but it does not erase it without allocating another array and filling it minus what you don't want.
Was This Post Helpful? 0
  • +
  • -

#6 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 - 11:06 AM

KYA: Not sure what you mean. I'm not reallocating any array, simply modifying the original. Since the original poster was talking about "strings" (which means null terminated in C), and he was asking to delete characters (make the string smaller), then there is nothing wrong with modifying the original. Why would you make a copy?

I'm not "blanking" any characters, they are being removed and any subsequent characters are being bumped down. I don't see how this is misleading.

Matthew
Was This Post Helpful? 0
  • +
  • -

#7 KYA  Icon User is offline

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

Reputation: 3120
  • View blog
  • Posts: 19,163
  • Joined: 14-September 07

Re: how to delete a character from a string

Posted 14 January 2009 - 11:08 AM

The amount of memory is consistent. It isn't truly erased. Example a vector can have an element erased and it will resize itself. Arrays can't do that.

edit: The thing I really didn't like about your example was passing 0 as length and then making length 1024 bytes long. This is an attempt to protect the user/other programmers from themselves, but if we have to do that then maybe we should be taking a different route entirely.

This post has been edited by KYA: 14 January 2009 - 11:17 AM

Was This Post Helpful? 0
  • +
  • -

#8 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 14 January 2009 - 11:20 AM

I have to agree with you both(matthew180 & KYA) in different ways.
KYA is completely right in that the memory allocation is the same and nothing is realy 'deleted', just changed(as matthew180 also points out).
But if you still want your maximum string length I'd say that reallocating the memory is just not necessary at all. Removing the chosen letters and bumping down the subsequent is a better method in this case.
But in the end is't just a matter of taste and is really up to the one writing the code witch he/she prefers.

EDIT: Didn't really read trough your code, just based the above statement on the non-codebased-text in your posts.

This post has been edited by Linkowiezi: 14 January 2009 - 11:24 AM

Was This Post Helpful? 0
  • +
  • -

#9 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 - 12:15 PM

View PostKYA, on 14 Jan, 2009 - 10:08 AM, said:

The amount of memory is consistent. It isn't truly erased. Example a vector can have an element erased and it will resize itself. Arrays can't do that.


Ah, I understand you comment now. Well, like Linkowiezi said, it has to be taken in context. If the length of the array is defined at compile time, then you don't want to resize it, and you certainly don't want to point the fixed array at a different memory location.

Without the original poster indicating that the arrays should be dynamic or static, then the example can never be complete.

Also, a "string" is defined by the sentinel NULL, not the allocated memory, so my example does actually change the size of the "string", however it does not adjust the allocated memory to be the same size as the "string" it contains.

View PostKYA, on 14 Jan, 2009 - 10:08 AM, said:

edit: The thing I really didn't like about your example was passing 0 as length and then making length 1024 bytes long. This is an attempt to protect the user/other programmers from themselves, but if we have to do that then maybe we should be taking a different route entirely.


I understand. I don't like unnecessarily duplicating data or processing an array more than once. We are different, and that makes the world a better place.

The functions were designed to accept a NULL terminated "string" (noted in the comments) in which case there is no need to pass the length. However, if you do know your buffer size and you are working with fixed length arrays, you can pass the length. The MAX_LENGTH is set with a #define that should be set to something logical based on the circumstances. My value was simply arbitrary for the example. I assume the programmer is aware of their data and their requirements.

A side affect of the length parameter is that it could be used to modify only part of the "string" and truncate anything past the indicated length. Could be handy.

Matthew
Was This Post Helpful? 0
  • +
  • -

#10 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 - 01:11 PM

Hey guys ... the OP said he was a beginner ... so give him some simple code please.

The presumption here, as a beginner, is that the OP will be using C strings like he said ...

He just wanted to delete a char from a simple C char string.

char s[] = "vishnu"; /* delete "i" from vishnu */


So ... with this kind of memory the program itself will handle the memory when it exits, if the 'i' is removed from the string 's' itself.

Shalom,
David
http://developers-he...index.php/topic,46.0.html
http://developers-he.../index.p...opic,106.0.html
Was This Post Helpful? 0
  • +
  • -

#11 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 - 01:22 PM

View PostDavid W, on 14 Jan, 2009 - 12:11 PM, said:

Hey guys ... the OP said he was a beginner ... so give him some simple code please.


Point taken.

Matthew

#include <stdio.h>

int
main(void)
{
	char s[] = "vishnu"; /* delete "i" from vishnu */
	char c;
	char *dst;
	int i;

	c = 'i';
	dst = s;

	printf("\nRemove '%c' from [%s]\n", c, s);

	for ( i = 0; s[i] != 0; i++ )
	{
		if ( s[i] != c )
			*dst++ = s[i];
	}

	// Ensure the string is null-terminated.
	*dst = 0;

	printf("[%s]\n\n", s);

	return 0;
}
// main()


This post has been edited by matthew180: 14 January 2009 - 01:23 PM

Was This Post Helpful? 1
  • +
  • -

#12 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 - 01:31 PM

That was very nice work ... Matt :)

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


p.s. You might like to comment a bit more ... for the beginner OP

    char s[] = "vishnu"; /* delete "i" from vishnu */
    char c ='i'; /* the char to remove is 'i' */
    char *dst=s; /* get a pointer to hold address of C string 's' */
    int i;

    printf("\nRemove '%c' from [%s]\n", c, s);

    for ( i = 0; s[i] != 0; i++ )
    {
        if ( s[i] != c )
            *dst++ = s[i]; /* Note: pointer only advanced if NOT 'i' */
    }

    /* Now at the proper 'end' pointer position ... null-terminate */
    *dst = 0;


This post has been edited by David W: 14 January 2009 - 01:43 PM

Was This Post Helpful? 1
  • +
  • -

#13 KYA  Icon User is offline

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

Reputation: 3120
  • View blog
  • Posts: 19,163
  • Joined: 14-September 07

Re: how to delete a character from a string

Posted 14 January 2009 - 01:38 PM

View Postmatthew180, on 14 Jan, 2009 - 12:15 PM, said:

View PostKYA, on 14 Jan, 2009 - 10:08 AM, said:

The amount of memory is consistent. It isn't truly erased. Example a vector can have an element erased and it will resize itself. Arrays can't do that.


Ah, I understand you comment now. Well, like Linkowiezi said, it has to be taken in context. If the length of the array is defined at compile time, then you don't want to resize it, and you certainly don't want to point the fixed array at a different memory location.

Without the original poster indicating that the arrays should be dynamic or static, then the example can never be complete.

Also, a "string" is defined by the sentinel NULL, not the allocated memory, so my example does actually change the size of the "string", however it does not adjust the allocated memory to be the same size as the "string" it contains.

View PostKYA, on 14 Jan, 2009 - 10:08 AM, said:

edit: The thing I really didn't like about your example was passing 0 as length and then making length 1024 bytes long. This is an attempt to protect the user/other programmers from themselves, but if we have to do that then maybe we should be taking a different route entirely.


I understand. I don't like unnecessarily duplicating data or processing an array more than once. We are different, and that makes the world a better place.

The functions were designed to accept a NULL terminated "string" (noted in the comments) in which case there is no need to pass the length. However, if you do know your buffer size and you are working with fixed length arrays, you can pass the length. The MAX_LENGTH is set with a #define that should be set to something logical based on the circumstances. My value was simply arbitrary for the example. I assume the programmer is aware of their data and their requirements.

A side affect of the length parameter is that it could be used to modify only part of the "string" and truncate anything past the indicated length. Could be handy.

Matthew



I see where you're coming from, but in your example, if enough items are done in that manner you'll corrupt the stack.


Quote

The presumption here, as a beginner, is that the OP will be using C strings like he said ...


I would never assume anything. Hopefully the OP will return with clarification.

This post has been edited by KYA: 14 January 2009 - 01:39 PM

Was This Post Helpful? 0
  • +
  • -

#14 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 - 01:50 PM

Quote

I would never assume anything. Hopefully the OP will return with clarification.


Good point ... after all this work for the OP, it would be nice if he would return :)

I noted that the OP didn't say if he was doing C or C++, but he DID ask for a simple way, as a beginner :)

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

P.S.

Your demo KYA, will be great to keep for future reference. :D

This post has been edited by David W: 14 January 2009 - 01:52 PM

Was This Post Helpful? 0
  • +
  • -

#15 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:00 PM

View PostKYA, on 14 Jan, 2009 - 12:38 PM, said:

I see where you're coming from, but in your example, if enough items are done in that manner you'll corrupt the stack.


Which manner are talking about and how would the stack get corrupted? Yes, if you pass a non null-terminated string you will probably buffer overflow, no doubt, but that is not unique to my code. Try passing a non null-terminated string to strcpy()...

C does not do any range checking, you always have to obey your bounds, and C is not a language for protecting the programmer from themselves.

Matthew
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2