Remove Duplicate Characters from Strings in an Array
Nov 29, 2016 at 2:41pm UTC
I am trying to remove the duplicate characters from strings in an array. The strings were read from a file. I had it output the array and that part I am successful on. After writing the function i received the error "error: cannot convert 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}' to 'char*' for argument '1' to 'void removeRepeats(char*, int)'removeRepeats (strings1[i], rows);" I tried changing the types around only to receive more errors. I changed the types back to the original in the code below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void removeRepeats (char strings1[], int rows);
int main()
{
char string_file[20];
cout << "What is the name of the file?\n" ;
cin >> string_file;
ifstream in_stream(string_file);
if (!in_stream)
{
cout << "file not open: " << string_file << '\n' ;
return 1;
}
const int rows = 20;
string strings1[rows];
int i = 0;
while (i<rows && getline(in_stream, strings1[i]))
{
i++;
}
for (int n=0; n<i; ++n)
removeRepeats (strings1[i], rows);
cout << strings1[i] << '\n' ;
in_stream.close();
}
void removeRepeats (char strings1[], int rows)
{
for (int i=0; i <rows; i++)
{
char c=strings1[i];
for (int j=i+1; j <rows; j++)
{
if (c==strings1[j])
strings1 [j]=' ' ;
}
}
}
Last edited on Nov 29, 2016 at 2:42pm UTC
Nov 29, 2016 at 5:13pm UTC
Try making your function look like this:
1 2 3 4 5 6 7 8 9 10
void RemoveRepeats(std::string &strings1, int rows)
{
...
for (int j = i + 1; j < rows; j++)
{
if (c == strings1[j])
strings1[j] = ' ' ;
}
...
}
Pass the string by reference so that you modify the original string and not a copy of the string.
Nov 29, 2016 at 9:51pm UTC
I'm still receiving the same error message after making the changes.
Nov 30, 2016 at 1:37am UTC
1 2 3
string strings1[rows];
void removeRepeats (char strings1[], int rows)
char string_file[20];
Consider using std::string, so to allow the user to enter an arbitrary length filename.
1 2
const int rows = 20;
string strings1[rows];
Similarly, I'd recommend you to use a std::vector here.
Nov 30, 2016 at 9:01am UTC
Removing duplicate characters from a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#include <iostream>
#include <string>
int main()
{
std::string str = "aaabbbccc" ;
const std::string::size_type size = str.size();
std::cout << str << "\n\n\n" ;
std::string chars;
unsigned short int index = 0;
for (char c : str)
{
if (chars.find(c) != std::string::npos)
{
str.erase(str.begin() + index);
str.resize(size);
}
else
{
chars.push_back(c);
}
++index;
}
str.shrink_to_fit();
std::cout << str << '\n' ;
std::cin.get();
return 0;
}
Last edited on Nov 30, 2016 at 9:37am UTC
Topic archived. No new replies allowed.