Reputation: 543
#include<iostream>
#include<memory.h>
#include<string.h>
using namespace std;
int main()
{
string a;
cin>>a;
int len=a.length();
bool hit[256];
memset(hit,0,sizeof(hit));
hit[a[0]]=1;
int tail=1;
for(int i=1;i<len;i++)
{
if(!hit[a[i]])
{
a[tail]=a[i];
++tail;
hit[a[i]]=true;
}
}
a[tail]='\0';
cout<<" "<<a;
}
This program removes duplicates in strings. For example an input of "aaaa"
will print only "a".
What I need to know is how to terminate the string in C++! It is not terminating with '\0'
. I read some questions on stackoverflow that indicate the termination of a string in c++ doesn't use '\0'
. I did not find how to terminate the strings instead. Can anyone help?
Upvotes: 0
Views: 477
Reputation: 2992
For removing duplicates you can use std::unique
here is the description of the function. It will return "An iterator to the element that follows the last element not removed". So you can resize your string using a.resize(i)
where i
is the return value of std::unique
.
Upvotes: 1
Reputation: 146940
Null-terminate a string is something you won't have to deal with with std::string
. Firstly, every function that accepts std::string
already knows the length and does not require NULL
termination. Secondly, std::string
has a c_str()
wrapper that provides a NULL
-terminated string for you, so you don't have to screw around with it. Just set the string to the length you want with resize
and it's done.
Upvotes: 4
Reputation: 13461
Just set the size of the string by string::resize
, no null-termination is needed:
a.resize(tail);
Upvotes: 1