Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. string trim

string trim

Scheduled Pinned Locked Moved C / C++ / MFC
question
8 Posts 6 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • T Offline
    T Offline
    tanarnelinistit
    wrote on last edited by
    #1

    If I have a string definfed as this: char sir[17] how can i remove any new line or carriage return from the end or the begining of it?

    _ J D Z 5 Replies Last reply
    0
    • T tanarnelinistit

      If I have a string definfed as this: char sir[17] how can i remove any new line or carriage return from the end or the begining of it?

      _ Offline
      _ Offline
      _AnsHUMAN_
      wrote on last edited by
      #2

      tanarnelinistit wrote

      remove any new line or carriage return

      void check(char p[])
      {
      	for(int i=0;i <   strlen(p)-1;i++)
      	{
      		if(p[i]=='\n')
      			//Don't copy to another location
                      else
                              // Copy char to another one
      // Similarly check for /r
      	}
      } 
      

      Somethings seem HARD to do, until we know how to do them. ;-)_AnShUmAn_

      1 Reply Last reply
      0
      • T tanarnelinistit

        If I have a string definfed as this: char sir[17] how can i remove any new line or carriage return from the end or the begining of it?

        J Offline
        J Offline
        James R Twine
        wrote on last edited by
        #3

        Go the end of the string, start backing up character-by-character while whitespace (or whatever you want to trim) is found.  When you find the first non-matching character, place a NUL into that location to terminate the string at that point.    You do not have to do something crazy like copying the string or moving it into and out of a string object.    Peace!

        -=- James


        If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
        Avoid driving a vehicle taller than you and remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
        DeleteFXPFiles & CheckFavorites (Please rate this post!)

        B 1 Reply Last reply
        0
        • T tanarnelinistit

          If I have a string definfed as this: char sir[17] how can i remove any new line or carriage return from the end or the begining of it?

          D Offline
          D Offline
          David Crow
          wrote on last edited by
          #4

          tanarnelinistit wrote:

          how can i remove any new line or carriage return from the...begining of it?

          Something like the following comes to mind:

          void TrimLeft( char *str, const char ch )
          {
          char *pStr = str;

          // locate first non-matching character
          while (ch == \*pStr)
              pStr++;
          
          strcpy(str, pStr);
          

          }

          Fine tune it to fit your needs.


          "Money talks. When my money starts to talk, I get a bill to shut it up." - Frank

          "Judge not by the eye but by the heart." - Native American Proverb

          1 Reply Last reply
          0
          • T tanarnelinistit

            If I have a string definfed as this: char sir[17] how can i remove any new line or carriage return from the end or the begining of it?

            Z Offline
            Z Offline
            Zac Howland
            wrote on last edited by
            #5

            Method using CString:

            char buffer[17] = {0};
            InitializeBuffer(buffer);	// put some value into it
            CString strBuffer(buffer);
            strBuffer.TrimLeft();
            strBuffer.TrimRight();
            memset(buffer, 0, 17);
            strncpy(buffer, strBuffer, 16);
            

            Method using std::string:

            char buffer[17] = {0};
            InitializeBuffer(buffer);	// put some value into it
            std::string sBuffer(buffer);
            int start_pos = sBuffer.find_first_not_of("\t\n\r ");
            int end_pos = sBuffer.find_last_not_of("\t\n\r ");
            if (start_pos == npos)
            {
            	start_pos = 0;
            }
            if (end_pos = npos)
            {
            	end_pos = strlen(buffer) - 1;
            }
            std::string sTemp = sBuffer.substr(start_pos, end_pos - start_pos + 1);
            memset(buffer, 0, 17);
            strncpy(buffer, sTemp.c_str(), 16);
            

            Method using char:

            int FindFirstNotOf(const char* chars, size_t chars_size, const char* str, size_t str_size)
            {
            	int ret = -1;
            	for (int i = 0; i < str_size; ++i)
            	{
            		bool bFound = false;
            		for (int j = 0; j < chars_size; ++j)
            		{
            			if (str[i] == chars[j])
            			{
            				bFound = true;
            				break;
            			}
            		}
            
            		if (bFound == false)
            		{
            			ret = i;
            			break;
            		}
            	}
            	
            	return ret;
            }
            
            int FindLastNotOf(const char* chars, size_t chars_size, const char* str, size_t str_size)
            {
            	int ret = -1;
            	for (int i = str_size - 1; i >= 0; --i)
            	{
            		bool bFound = false;
            		for (int j = 0; j < chars_size; ++j)
            		{
            			if (str[i] == chars[j])
            			{
            				bFound = true;
            				break;
            			}
            		}
            
            		if (bFound == false)
            		{
            			ret = i;
            			break;
            		}
            	}
            	
            	return ret;
            }
            
            char buffer[17] = {0};
            InitializeBuffer(buffer);	// put some value in there
            char chars[5] = "\t\r\n ";
            int start_pos = FindFirstNotOf(chars, 5, buffer, 17);
            int end_pos = FindLastNotOf(chars, 5, buffer, 17);
            
            if (start_pos == -1)
            {
            	start_pos = 0;
            }
            
            if (end_pos == -1)
            {
            	end_pos = strlen(buffer) - 1;
            }
            
            char newBuffer[17] = {0};
            strncpy(newBuffer, &buffer[start_pos], end_pos - start_pos);
            memset(buffer, 0, 17);
            strncpy(buffer, newBuffer, 16);
            

            If you decide to become a software engineer, you are signing up to have a 1/2" piece of silicon tell you exactly how stupid you really are for 8 hours a day, 5 days a week Zac

            1 Reply Last reply
            0
            • T tanarnelinistit

              If I have a string definfed as this: char sir[17] how can i remove any new line or carriage return from the end or the begining of it?

              J Offline
              J Offline
              James R Twine
              wrote on last edited by
              #6

              OK - perhaps a simple example of trimming a string in-place, because you did not mention the word "copy" in your post (this code comes slightly modified from my TStaticString class):

              void TrimRight( LPTSTR cpString,
              LPCTSTR cpTrimWhat = _T( " " ) ) // Trim Trailing Characters From String
              {
              size_t stStrLen = ::_tcslen( cpString ); // Get String Length

              if( !stStrLen )                                     // If No String Length
              {
                  return;                                         // Stop Here
              }
              LPTSTR  cpCursor = ( cpString + ( stStrLen - 1 ) ); // Start At End Of String (Not The NUL Terminator)
              size\_t  stCount = 0;
              
              while( ( stCount < stStrLen) &&                     // While String Characters Available
                      ( ::\_tcschr( cpTrimWhat, \*cpCursor ) ) )    // Look For Target To Remove
              {
                  ++stCount;                                      // Increment Count While Found
                  --cpCursor;                                     // Decrement Cursor Location
              }
              if( stCount )                                       // If Trimming Characters Found
              {
                  ++cpCursor;                                     // Advance Cursor Back To Last Trailing Character
                  \*cpCursor = \_T( '\\0' );                         // Terminate The String Right There
              }
              return;                                             // Done!
              

              }

              See how that works for you.  Specify the characters to   Example of use:

              TCHAR   caTest\[ 32 \];
              
              strcpy( caTest, \_T( "abc\\t   " ) );
              TrimRight( caTest );
              strcpy( caTest, \_T( "abc\\t   " ) );
              TrimRight( caTest, "\\t " );
              

              The first call will trim up to the tab character, the second will also trim the tab character.    Peace!

              -=- James


              If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
              Avoid driving a vehicle taller than you and remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
              DeleteFXPFiles & CheckFavorites (Please rate this post!)

              1 Reply Last reply
              0
              • J James R Twine

                Go the end of the string, start backing up character-by-character while whitespace (or whatever you want to trim) is found.  When you find the first non-matching character, place a NUL into that location to terminate the string at that point.    You do not have to do something crazy like copying the string or moving it into and out of a string object.    Peace!

                -=- James


                If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
                Avoid driving a vehicle taller than you and remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
                DeleteFXPFiles & CheckFavorites (Please rate this post!)

                B Offline
                B Offline
                Blake Miller
                wrote on last edited by
                #7

                What about beginning of string?

                Any sufficiently gross incompetence is nearly indistinguishable from malice.

                J 1 Reply Last reply
                0
                • B Blake Miller

                  What about beginning of string?

                  Any sufficiently gross incompetence is nearly indistinguishable from malice.

                  J Offline
                  J Offline
                  James R Twine
                  wrote on last edited by
                  #8

                  Just reverse the algorithm, being sure not to walk past the end of the string.    Peace!

                  -=- James


                  If you think it costs a lot to do it right, just wait until you find out how much it costs to do it wrong!
                  Avoid driving a vehicle taller than you and remember that Professional Driver on Closed Course does not mean your Dumb Ass on a Public Road!
                  DeleteFXPFiles & CheckFavorites (Please rate this post!)

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups