0
#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?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
user2416871
  • 543
  • 1
  • 4
  • 13

3 Answers3

4

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Puppy
  • 144,682
  • 38
  • 256
  • 465
1

Just set the size of the string by string::resize, no null-termination is needed:

a.resize(tail);
Juraj Blaho
  • 13,301
  • 7
  • 50
  • 96
1

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Alexandru Barbarosie
  • 2,952
  • 3
  • 24
  • 46