cutting characters off a string
I wish to cut four characters off the end of a string, and replace them with a different four characters, these strings are variable in length and I''m using C++. Is there an easy and efficient way to do this?
I think that would depend entirely on how you are storing the strings.
Assuming the typical NULL terminated strings in C/C++..
May need slight modification for your exact environment and surrounding code, of course. Incidentally, the while loop is pretty much the same thing strlen() does, but this code does it more directly.
/* CODE FRAGMENT */char * string_to_mangle;int string_index = 0;while( string_to_mangle[string_index++] ) ; /* Do nothing, the work is done in the while test */string_index -= 5; /* subtract 5, to account for the NULL *//* At this point, string_to_mangle[string_index] will point to the 4th char from the end of the string, so you can do what you want to it.. EG: (assume stdio.h, string.h, etc) */strcpy( &string_to_mangle[string_index], "1234" );printf( "%s\n", string_to_mangle );/* Should print the input string, with the last four chars replaced with "1234" */
May need slight modification for your exact environment and surrounding code, of course. Incidentally, the while loop is pretty much the same thing strlen() does, but this code does it more directly.
just get the actual strlen(string) and then count backwards replacing the characters in the last 4 fields.
szString[ WANTED_LENGTH ] = ''\0'';
[s]--------------------------------------------------------[/s]chromecode.com - software with source code
C++ strings have a replace member function.
Use it, that''s what it has been designed to do.
[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
Use it, that''s what it has been designed to do.
[ Start Here ! | How To Ask Smart Questions | Recommended C++ Books | C++ FAQ Lite | Function Ptrs | CppTips Archive ]
[ Header Files | File Format Docs | LNK2001 | C++ STL Doc | STLPort | Free C++ IDE | Boost C++ Lib | MSVC6 Lib Fixes ]
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement