So in my class we are learning about strings. In this program, the goal is to reformat the text in a data file.

sample data file:

Here's a "TEST" file. (DateD 5 April, 2012)
Will this #*PrOGRAM+=@ that includes
!user-defined?!?> FUNCTIONS
really work? Only time will

My program needs to delete the non alphanumeric characters that are at the beginning and end of each word.
For instance: "TEST" needs to be changed to TEST.
I can't use the isalpha to delete all nonalphanumeric characters because the ones inside each word are to be kept
For instance: !user-defined?!?> needs to be changed to user-defined

I've been trying to devise a way to do this but I can't figure this out.

Here's the code for the function.Thanks!

string characters(string text)
  int n=text.length();
  string newtext;
  for (int i=0; i<n; i++)
      while (!isalnum(text[0]))
        for (int j=1; j<n; j++)
      while (!isalnum(text[n-1]))
        for(int k=0; k<n-2; k++)
  return newtext;

It's really just a customized trim algorithm. Search from the beginning until you find a valid character, then mark that position. Search from the end as well until you find a valid character and mark that position. Now you have enough information to extract a substring:

#include <iostream>
#include <string>
#include <sstream>

#include <cctype>

using namespace std;

string sanitize(string const& s, int valid_character(int))
    string::size_type first = 0;
    string::size_type last = s.size();

    // Skip leading and trailing invalid characters
    while (first != s.size() && !valid_character(s[first]))

    while (last != 0 && !valid_character(s[last - 1]))

    // Trim and remove the located invalid characters (leave embedded "invalid" characters)
    return s.substr(first, last - first);

int main()
    istringstream src(
        "Here's a \"TEST\" file. (DateD 5 April, 2012)\n"
        "Will this #*PrOGRAM+=@ that includes\n"
        "!user-defined?!?> FUNCTIONS\n"
        "really work? Only time will\n"
    string word;

    while (src >> word)
        cout << sanitize(word, isalnum) << '\n';
This article has been dead for over six months. Start a new discussion instead.