-
Changing strings
I'm trying to take a string and take out any character that isnt a letter so all that is left is the letters with no spaces.
Code:
string line, nospc, nodigit;
int j = 0;
line = "jggg665 ugigigh";
nospc = line;
int len = line.length();
for (int i=0; i<len; i++)
{
if (isalnum(line[i]))
{
nospc [j] = line [i];
j = j + 1;
}
}
Thats what the code I came up with looks like.
I tried to get rid of the spaces in the line string but what it printed out was the same thing, only with the spaces filled in with letters. I want the letters after the spaces to simply move over.
I've been stuck on this for hours.
Any help is very welcome!
-
It's because your making nospace equal to the original line and then overwriting nospace with the shortened line. This ofcourse will leave the extra characters at the end.
You're using string objects... take advantage of their features. They have an overloaded + operator, so instead of wasting your time creating indexed values for an empty string to work with. Just keep adding the good character to nospc.
Code:
string line, nospc;
line = "jggg665 ugigigh";
int len = line.length();
for (int i=0; i<len; i++) {
if (isalnum(line[i])) {
nospc += line[i];
j++;
}
}
-
since you're using strings, slymaelstrom has a good point. But what it looks like to me is that you keep forgetting to move the null up. A simple way to do that is wait until the loop is done and throw a '\0' into the string. The rest of the letters will still be there, but they won't show up.
Again, if you're using C++ strings, I wouldn't do it this way - this is more of a C-style string thing.
-
Thanks for the replies, I did end up getting it to work.
However now its gone to crazy on me.
Code:
#include <iostream>
#include <string>
#include <fstream>
#include <cctype>
using namespace std;
string readLineFromFile (string&);
string cleanString (const string& line);
int main( void )
{
string line, nospc, cleaned;
int j = 0;
int y = 0;
nospc="";
cleaned="";
line = "akj832 adf83";
int len = line.length();
for (int i=0; i<len; i++)
{
if (isalnum(line[i]))
{
nospc = nospc + line [i];
}
}
int len2 = nospc.length();
for (int h=0; h<len2; h++)
{
cleaned[h] = tolower(cleaned[h]);
}
cout << cleaned ;
return 0;
}
Thats the code I have so far (ignore the functions, they will be added later) and for me it comes up with an "unhandled exception" and the program crashes when I try to run it. I can't figure out what is wrong with it. Any suggestions?
Note: If I put something into the cleaned string at the begining it works.
-