字符数组排序和删除重复项

use*_*660 0 c++ arrays

我正在尝试做一些数组操作.我在这里做char数组排序和重复删除.欢迎您的意见.尽管如此,还没有做过很多测试和错误处理.

#include<stdafx.h>
#include<stdlib.h>
#include<stdio.h>
#include<string>
using namespace std;

void sort(char *& arr)
{
    char temp;
    for(int i=0;i<strlen(arr);i++)
    {
        for(int j=i+1;j<strlen(arr);j++)
        {
            if(arr[i] > arr[j])
            {
            temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
            }
        }
    }

}
bool ispresent(char *uniqueArr, char * arr)
{
    bool isfound = false;
    for(int i=0;i<strlen(arr);i++)
    {
    for(int j=0;j<=strlen(uniqueArr);j++)
    {
        if(arr[i]== uniqueArr[j])
        {
        isfound = true;
        return isfound;
        }
        else
        isfound = false;
    }
    }

    return isfound;
}

char * removeduplicates(char *&arr)
{
    char * uniqqueArr = strdup(""); // To make this char array modifiable
    int index = 0;
    bool dup = false;
    while(*arr!=NULL)
    {       
     dup = ispresent(uniqqueArr, arr);
     if(dup == true)
     {}//do nothing
     else// copy the char to new char array.
     {
           uniqqueArr[index] = *arr;    
     index++;
     }
    arr++;
    }
    return uniqqueArr;
}
int main()
{
    char *arr = strdup("saaangeetha"); 
    // if strdup() is not used , access violation writing to 
          //location occurs at arr[i] = arr[j]. 
    //This makes the constant string modifiable
    sort(arr);
    char * uniqueArr = removeduplicates(arr);   

}
Run Code Online (Sandbox Code Playgroud)

Naw*_*waz 6

如果你使用std::string,你的代码(实际上是C风格)可以用这些代码用C++ Style编写:

#include <iostream>
#include <string>
#include <algorithm>

int main() {
        std::string s= "saaangeetha";
        std::sort(s.begin(), s.end());
        std::string::iterator it = std::unique (s.begin(), s.end()); 
        s.resize( it - s.begin());
        std::cout << s ;
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出:(删除所有重复项)

aeghnst
Run Code Online (Sandbox Code Playgroud)

演示:http://ideone.com/pHpPh

如果你想char*在最后,那么你可以这样做:

   const char *uniqueChars = s.c_str(); //after removing the duplicates!
Run Code Online (Sandbox Code Playgroud)