Thread: How do you delete the last element of a string in C++?

  1. #1
    Registered User
    Join Date
    Mar 2008
    Posts
    1

    How do you delete the last element of a string in C++?

    How do you delete the last element of a string in C++? Thnx!

  2. #2
    Registered User
    Join Date
    Nov 2007
    Posts
    57
    http://cplusplus.com/reference/string/string/erase.html
    http://cplusplus.com/reference/string/string/size.html

    If you use size as an argument, you can delete the last character in the string. Not sure how, never used the erase() function.

  3. #3
    Jack of many languages Dino's Avatar
    Join Date
    Nov 2007
    Location
    Chappell Hill, Texas
    Posts
    2,332
    You can erase the last char, or truncate the length of the string.

    Todd
    Mainframe assembler programmer by trade. C coder when I can.

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    #include <iostream>
    #include <string>
    
    int main ( void )
    {
    	std::string str("Hello World!");
    
    	std::cout << "Before: \"" << str << '\"' << std::endl;
    
    	str.resize(str.size()-1);
    
    	std::cout << "After : \"" << str << '\"' << std::endl;
    
    	return 0;
    }
    Output:
    Code:
    Before: "Hello World!"
    After : "Hello World"
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  5. #5
    Weak. dra's Avatar
    Join Date
    Apr 2005
    Posts
    166
    just for reference:

    http://cppreference.com/cppstring/index.html

    std::string has an erase function that can remove a character from a string.

    deleting the last element would be like so:

    Code:
    std::string str = "hello";
    
    str.erase(str.end() - 1);
    
    std::cout << str; // "hell"

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  2. Replies: 4
    Last Post: 03-03-2006, 02:11 AM
  3. can anyone see anything wrong with this code
    By occ0708 in forum C++ Programming
    Replies: 6
    Last Post: 12-07-2004, 12:47 PM
  4. Something is wrong with this menu...
    By DarkViper in forum Windows Programming
    Replies: 2
    Last Post: 12-14-2002, 11:06 PM