I was trying to implement a function that will modify a string:
The code is as follows:
test.h file :
#ifndef header_file
#define header_file
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
char * findWord(char *, char *);
#endif
test.c file:
#include"test.h"
char * findWord(char *array, char *action)
{
char testchar;
int count=0, i=0, j, start = 0, end, wordLength = 0, charCount =0, k=0;
char *temp = malloc(sizeof(char)*400);
char *word = malloc(sizeof(char)*30);
char *replaceString = malloc(sizeof(char)*80);
if(strcmp(action,"replace") == 0)
{
while((testchar = array[i]) != '\0')
{
if(testchar == ',')
{
start = i+1;
i++;
continue;
}
else if(testchar == ':')
{
end = i;
word[charCount] = '\0';
charCount = 0;
printf("Start is: %d \n", start);
for(j=0; j< strlen(array); j++)
{
if(j == start)
{
sprintf(replaceString, "%s%s%s", "replace_",word,"_ii");
printf("Replace String for word %s is %s.\n",word,replaceString);
strcat(temp,replaceString);
j = (j-1)+(strlen(word));
k= strlen(replaceString);
printf("The value of J is %d for word %s.\n",j,word);
}
else
{
temp[k++] = array[j];
}
}
temp[k] = '\0';
k=0;
printf(" Words %s is replaced. The new string is:\n", word);
printf("%s\n",temp);
memset(word,'0',30);
memset(temp,'0',400);
memset(replaceString,'0',80);
i++;
continue;
}
if(testchar != 'Y')
{
word[charCount] = testchar;
charCount++;
}
i++;
}
}
else if(strcmp(action,"MISSING") == 0)
{
}
else if(strcmp(action,"EMPTY") == 0)
{
}
else
printf("Something went wrong.\n");
free(temp);
free(word);
free(replaceString);
}
main.c file:
#include"test.h"
int main()
{
char sc[] = "cn:Y,x509UniqueIdentifier:Y,pseudonym:Y,name:Y,l:Y,street:Y,state:Y,postalAddress:Y,postalCode:Y,telephoneNumber:Y,emailAddress:Y";
findWord(sc, "replace");
return 0;
}
The expected output is:
Replace String for word cn is replace_cn_ii.
replace_cn_ii:Y,x509UniqueIdentifier:Y,pseudonym:Y,name:Y,l:Y,street:Y,state:Y,postalAddress:Y,postalCode:Y,telephoneNumber:Y,emailAddress:Y
.
.
.
10 output.
But It is giving the garbage value due to unexpected behavior of strlen().
The value of word after strcat() function is changed automatically.
Where am I going wrong?
Let me know the issue and how to fix it.
Thanks!
You're calling strcat() on temp, but temp does not contain a valid string. This gives undefined behavior.
You must make sure temp is valid first, i.e. make it an empty string:
*temp = '\0';
Of course you must also make sure the allocation has succeeeded.
Related
source code
/***************************************************
* Copyright: 2023, 黄子涵.
* File name: huangzihan_c_program_142
* Description: 改变指针的值
* Author: 黄子涵
* Version: V1.0.0
* Date: 2023-01-08
* ****************************************************/
#include <stdio.h>
char huangzihan[10];
char huangchunqin[12];
char chenlanying[12];
char shejiazi[8];
void name_input();
void name_output();
void name_output_n();
void name_input()
{
int i;
printf("*********************************\n");
printf(" 给字符数组输入对应的名字 \n");
printf("*********************************\n");
printf("请输入黄子涵的小写拼音:");
for (i = 0; i < 10; i++)
{
scanf("%c", &huangzihan[i]);
if (huangzihan[i] == 10)
{
huangzihan[i] = '\0';
break;
}
}
getchar();
printf("请输入黄春钦的小写拼音:");
for (i = 0; i < 12; i++)
{
scanf("%c", &huangchunqin[i]);
if (huangchunqin[i] == 10)
{
huangchunqin[i] = '\0';
break;
}
}
getchar();
printf("请输入陈兰英的小写拼音:");
for (i = 0; i < 11; i++)
{
scanf("%c", &chenlanying[i]);
if (chenlanying[i] == 10)
{
chenlanying[i] = '\0';
break;
}
}
getchar();
printf("请输入佘佳梓的小写拼音:");
for (i = 0; i < 8; i++)
{
scanf("%c", &shejiazi[i]);
if (shejiazi[i] == 10)
{
shejiazi[i] = '\0';
break;
}
}
printf("\n");
}
void name_output()
{
char *p1,*p2,*p3,*p4;
printf("*********************************\n");
printf(" 将字符数组对应的名字输出 \n");
printf("*********************************\n");
printf("输出huangzihan:");
p1 = huangzihan;
printf("%s", p1);
printf("\n");
printf("输出huangchunqin:");
p2 = huangchunqin;
printf("%s", p2);
printf("\n");
printf("输出chenlanying:");
p3 = chenlanying;
printf("%s", p3);
printf("\n");
printf("输出shejiazi:");
p4 = shejiazi;
printf("%s", p4);
printf("\n");
}
void name_output_n()
{
int i;
char *p;
printf("\n");
printf("*********************************\n");
printf(" 改变指针的值 \n");
printf("*********************************\n");
printf("你要从第几个字符输出huangzihan(共10个字符)?");
scanf("%d", &i);
p = huangzihan + i - 1;
printf("这是你要输出的字符串:%s", p);
printf("\n");
printf("你要从第几个字符输出huangchunqin(共12个字符)?");
scanf("%d", &i);
p = huangchunqin + i - 1;
printf("这是你要输出的字符串:%s", p);
printf("\n");
printf("你要从第几个输出chenlanying(共11个字符)?");
scanf("%d", &i);
p = chenlanying + i - 1;
printf("这是你要输出的字符串:%s", p);
printf("\n");
printf("你要从第几个输出shejiazi(共8个字符)?");
scanf("%d", &i);
p = shejiazi + i - 1;
printf("这是你要输出的字符串:%s", p);
printf("\n");
}
int main()
{
extern char huangzihan[10];
extern char huangchunqin[12];
extern char chenlanying[12];
extern char shejiazi[8];
name_input();
name_output();
name_output_n();
return 0;
}
At first, I thought it was the problem of not adding the end tag of the string, but I added the end tag of the string and found it didn't work.Add code as follows:
if (shejiazi[i] == 10) {
shejiazi[i] = '\0';
break;
}
I want to output results
输出huangzihan:huangzihan
输出huangchunqin:huangchunqin
输出chenlanying:chenlanying
输出shejiazi:shejiazi
Actual output results
I want to know why this happens. If you know, please tell me. Thank you very much。
If the input string has exactly the maximum number of characters, the target array is not null terminated, causing printf("...%s", ...) to have undefined behavior. If your case it seems the arrays huangchunqin and chenlanying are adjacent in memory, so printf("%s",p2); outputs the contents of huangchunqin until it finds a null terminator, which does not occur before the end of chenlanying.
You should make the arrays one byte longer and use a function to read these strings:
/* Author: 查理戈登 */
/* Description: 程序的修改版本 */
#include <stdio.h>
char huangzihan[11];
char huangchunqin[13];
char chenlanying[13];
char shejiazi[9];
// read a string into a char array of a given length,
// return EOF if no input at end of file, 1 if truncated, 0 otherwise
int input_string(const char *prompt, char *dest, size_t size) {
size_t i = 0;
int c;
int result = 0;
printf("%s: ", prompt);
while ((c = getchar()) != EOF && c != '\n') {
if (i + 1 < size) {
dest[i++] = c;
} else {
result = 1;
}
}
dest[i] = '\0';
if (i == 0 && c == EOF)
result = EOF;
return result;
}
void name_input(void) {
printf("*********************************\n");
printf(" 给字符数组输入对应的名字 \n");
printf("*********************************\n");
// Qǐng shūrù shéjiāzǐ de xiǎoxiě pīnyīn
input_string("请输入黄子涵的小写拼音", huangzihan, sizeof huangzihan);
input_string("请输入黄春钦的小写拼音", huangchunqin, sizeof huangchunqin);
input_string("请输入陈兰英的小写拼音", chenlanying, sizeof chenlanying);
input_string("请输入佘佳梓的小写拼音", shejiazi, sizeof shejiazi);
printf("\n");
}
In name_input() you don't terminate your strings correctly as the last iteration is i=9:
for(i=0;i<10;i++) {
scanf("%c",&huangzihan[i]);
if(huangzihan[i]==10)
{
huangzihan[i]='\0';
break;
}
}
Instead you could do:
int i = 0;
for(; i < sizeof huangzihan - 1; i++) {
scanf("%c", &huangzihan[i]);
}
huangzihan[i] = '\0';
I don't know if your letters entered fit into the char if not you will get some weird corruption.
You can also just read a string with:
#define huangzihan_len 9
#define str(s) str2(s)
#define str2(s) #s
char huangzihan[huangzihan_len+1];
//...
scanf("%" str(huangzihan_len) "s", huangzihan);
After reading a string you do getchar() presumably to get rid of the newline. You can change the format string with an initial space to do that automatically " %c", or make a flush function that discards all data till you hit a new line:
void flush() {
for(;;) {
int ch = getchar();
if(ch == EOF || ch == '\n') return;
}
}
Your code is repetitive so consider using an array to hold your strings, as they are different length perhaps an array of string pointers char *str[4]?
I have problem with my alignement. This time I want my program to return words that ends and starts with the same letter. I've wrote something like this, but it seems to return random words.
#include <stdio.h>
#include <string.h>
void main()
{
char str[100];
int i, t, j, len;
printf("Enter a string : ");
scanf("%[^\n]s", str);
len = strlen(str);
str[len] = ' ';
for (t = 0, i = 0; i < strlen(str); i++)
{
if ((str[i] == ' ') && (str[i - 1] == str[0]))
{
for (j = t; j < i; j++)
printf("%c", str[j]);
t = i + 1;
printf("\n");
}
else
{
if (str[i] == ' ')
{
t = i + 1;
}
}
}
}
You can use strtok to split the strings from stdin, then apply a letter checker on each parsed word one at a time.
Something like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define MAXCHAR 100
int is_start_end(char *word);
void exit_if_null(void *ptr, const char *msg);
int
main(void) {
char str[MAXCHAR];
char *word;
char **all_words;
int words_size = 1, word_count = 0;
int i, found;
all_words = malloc(words_size * sizeof(*all_words));
exit_if_null(all_words, "initial Allocation");
printf("Enter words(enter empty line to terminate):\n");
while (fgets(str, MAXCHAR, stdin) != NULL && strlen(str) != 1) {
word = strtok(str, " \n");
while (word !=NULL) {
if (words_size == word_count) {
words_size *= 2;
all_words = realloc(all_words, words_size * sizeof(*all_words));
exit_if_null(all_words, "Reallocation");
}
all_words[word_count] = malloc(strlen(word)+1);
exit_if_null(all_words[word_count], "Initial Allocation");
strcpy(all_words[word_count], word);
word_count++;
word = strtok(NULL, " \n");
}
}
printf("Words that have equal first and last letters:\n");
found = 0;
for (i = 0; i < word_count; i++) {
if (is_start_end(all_words[i])) {
found = 1;
printf("%s\n", all_words[i]);
}
free(all_words[i]);
all_words[i] = NULL;
}
if (found == 0) {
printf("None Found\n");
}
free(all_words);
all_words = NULL;
return 0;
}
int
is_start_end(char *word) {
int len;
len = strlen(word);
if ((len == 1) || (tolower(word[0]) == tolower(word[len-1]))) {
return 1;
}
return 0;
}
void
exit_if_null(void *ptr, const char *msg) {
if (!ptr) {
printf("Unexpected null pointer: %s\n", msg);
exit(EXIT_FAILURE);
}
}
This line removes the null terminator of the string:
len = strlen(str);
str[len] = ' ';
thus the string no longer exists, what is left is just an ordinary array of characters.
The next call to strlen, in the body of the for loop, will cause undefined behavior.
I'm making a program to delete extra spaces in c and count how many extra space it deletes. The program counts the extra spaces but it doesn't print the string that doesn't have extra spaces. I'll show you my code:
#include <stdio.h>
#include <stdlib.h>
/*
*
*/
char delete_spaces(char oracion[100])
{
int i;
for (i=0;oracion[i]!='\0';i++){
if (oracion[i]==' '&&oracion[i+1]==' '){
oracion[i]=oracion[i+1];
}
}
return(oracion[100]);
}
int count_spaces(char oracion[100])
{
int i,number_spaces=0;
for (i=0;oracion[i]!='\0';i++){
if (oracion[i]==' '&&oracion[i+1]==' '){
number_spaces+=1;
}
}
return(number_spaces);
}
int main(void){
char frase[100],frase2[100];
int num_spaces;
printf("Write here the phrase:");
gets(frase);
frase2[100]=delete_spaces(frase);
num_spaces=count_spaces(frase);
printf("%s",frase2);
printf("%d",num_spaces);
return 0;
}
Could be this what you need?:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int delete_spaces(char *s1,char *s2){
int found = 0;
int i = 0, j = 0;
while(s1[i] != '\0'){
if (((s1[i] == ' ') && (s1[i+1] == ' ')) || ((s1[i] == '\t') && (s1[i+1] == '\t'))){
found++;
} else {
s2[j++] = s1[i];
}
i++;
}
s2[j] = '\0';
printf("s2 = %s\n",s2);
return found;
}
int main(void){
char frase[100], frase2[100];
int num_spaces;
printf("Write here the phrase:");
if((fgets(frase,99,stdin)) == NULL){
printf("Error\n");
}
num_spaces=delete_spaces(frase,frase2);
printf("Number of deleted spaces = %d\n",num_spaces);
return 0;
}
Output:
I'm going to sleep now Goodbye
s2 = I'm going to sleep now Goodbye
Number of deleted spaces = 13
In addition to Barmar's suggestion above, you probably want frase2 to actually be a char* type, and you want to assign it not to the index 100, but the pointer itself:
int main(void) {
char frase[100];
char *frase2;
...
frase2 = delete_spaces(frase);
...
}
You can't assign to an array the way you're trying to do it. You should pass frase2 as a second argument to the function. Then it can copy from one array to the other, skipping over duplicate spaces.
int delete_spaces(char oracion[100], char oracion2[100])
{
int deletions = 0;
int i;
int dest = 0;
for (i=0; oracion[i]!='\0'; i++){
if (oracion[i]==' '&&oracion[i+1]==' '){
deletions++;
} else {
oracion2[dest++] = oracion[i];
}
}
oracion2[dest] = '\0'; // don't forget to terminate the string
return deletions;
}
Notice that this does the counting as it's deleting, so you don't need a separate function for this.
Then you would call it from main as:
num_spaces = delete_spaces(frase, frase2);
#include <stdio.h>
#include <stdlib.h>
typedef struct sentence {//wrap by struct
char oracion[100];
} sentence;
sentence delete_spaces(sentence frase)//make copy
{
int i, j;
for (j=i=0; frase.oracion[i] != '\0'; i++){
if(j && frase.oracion[j-1] == ' ' && frase.oracion[i] == ' '){
continue;
}
frase.oracion[j++] = frase.oracion[i];
}
frase.oracion[j] = '\0';
return frase;
}
int count_spaces(sentence frase)
{
int i, j, number_spaces = 0;
for (j=i=0; frase.oracion[i] != '\0'; i++){
if(j && frase.oracion[j-1] == ' ' && frase.oracion[i] == ' '){
number_spaces += 1;
continue;
}
frase.oracion[j++] = frase.oracion[i];
}
return number_spaces;
}
int main(void){
sentence frase, frase2;
int num_spaces;
printf("Write here the phrase:");
scanf("%99[^\n]%*c", frase.oracion);
frase2 = delete_spaces(frase);//make copy to frase2
num_spaces = count_spaces(frase);
printf("%s\n", frase2.oracion);
printf("%d\n", num_spaces);
return 0;
}
I'm trying to implement a simple lexical analyzer in C. And my problem is about characters and strings. Normally in my linked list insertion I give char as an argument. But in the keyword case since they are string while printing them, I'm having problems:
#define _CRT_SECURE_NO_DEPRECATE
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#define MAX 50
char token[MAX];
char ch, str[25];
//Structure definition for lexemes
struct lexeme{
char lexemes;
char tokenclass[MAX];
struct lexeme *next;
};
typedef struct lexeme lexeme;
lexeme *firstPtr = NULL;
lexeme *lastPtr = NULL;
//This method is for inserting the values into linked list.
void insert(char s, char *t){
lexeme *np;
np = malloc(sizeof(lexeme));
np->lexemes = s;
strcpy(np->tokenclass, t);
np->next = NULL;
if (firstPtr == NULL){
firstPtr = np;
}
else{
lastPtr->next = np;
}
lastPtr = np;
}
/*void insert_key(char *kyw, char *t){
lexeme *kp;
kp = malloc(sizeof(lexeme));
kp->lexemes
}*/
void keyw(char *p);
int i = 0;
//Array of keywords
char keys[12][10] = { "break", "char", "continue",
"double", "else", "end", "for", "if", "int", "return", "void", "while" };
int main() {
char seps[13] = " \n,;(){}[]\"";
char oper[] = "!%^&*-+=~|.<>/?";
int j;
//char fname[200];
FILE *f1;
//clrscr();
fopen_s(&f1, "input.txt", "r");
if (f1 == NULL)
{
printf("file not found");
}
while ((ch = fgetc(f1)) != EOF)
{
for (j = 0; j <= 14; j++)
{
if (ch == oper[j])
{
printf("%c is an operator\n", ch);
strcpy(token, "operator");
insert(ch, token);
str[i] = '\0';
keyw(str);
}
}
for (j = 0; j <= 12; j++)
{
/* if(i==-1)
break;*/
if (ch == seps[j])
{
// if(strcmp(ch,"==") || strcmp(ch,"<=") || strcmp(ch,">=") || strcmp(ch,"<")|| strcmp(ch,">") || strcmp(ch,"?="))
// printf("%s is a logical operator",ch);
str[i] = '\0';
keyw(str);
}
}
if (i != -1)
{
str[i] = ch;
i++;
}
else
i = 0;
}
printf("(");
while (firstPtr != NULL){
printf("%c,", firstPtr->lexemes);
printf("%s |", firstPtr->tokenclass);
//printf("---- %c,%s ---- \n", firstPtr->next->lexemes, firstPtr->next->tokenclass);
firstPtr = firstPtr->next;
}
printf(")");
printf("\n");
printf("\n");
system("pause");
return 1;
}
void keyw(char *p)
{
int k, flag = 0;
for (k = 0; k <= 11; k++)
{
if (strcmp(keys[k], p) == 0)
{
printf("%s is a keyword\n", p);
strcpy(token, "keyword");
insert(p[0], token);
flag = 1;
break;
}
}
if (flag == 0)
{
if (isdigit(p[0]))
{
printf("%s is a number\n", p);
strcpy(token, "number");
insert(p[0], token);
}
else
{
if (p[0] != '\0')
{
printf("%s is an identifier\n", p);
strcpy(token, "id");
insert(p[0], token);
}
}
}
i = -1;
}
While my input is:
int a=5;
int b=3;
int c;
if(a>b){
c=7;
b=c+a;
end
}
Normally I get my output like this:
<i,keyword |=,operator |>,operator |a,id |5,number |i,keyword |=,operator |b,id |3,number |i, keyword |c,id | .... and so on.
I know that I shouldn't give p[0] in the case of keywords. I also examined my struct definition and made my char lexemes to char lexemes[] but I got some errors. I tried to find proper str class of C but I couldn't.
I want my output like:
( int,keyword ) (i,keyword) instead
So what do you suggest? What should I do to achieve it?
my suggestion : keyword save as a number.
Registration part
if (strcmp(keys[k], p) == 0)
{
printf("%s is a keyword\n", p);
strcpy(token, "keyword");
insert(k, token);//insert(p[0], token);
flag = 1;
break;
}
print part
if(firstPtr->lexemes < 12)
printf("%s,", keys[firstPtr->lexemes]);
else
printf("%c,", firstPtr->lexemes);
printf("%s |", firstPtr->tokenclass);
I wrote the following function for removing duplicate characters from a string..For ex: if
str = "heeello;
removeDuplicate(str)
will return helo...But it shows some error on runtime .I have added some printf() statements for debugging...Can anyone tell me what the problem is ?
char* removeDuplicate(char str[])//remove duplicate characters from a string,so that each character in a string is not repeating
{
int i = 0,j;
char ch;
printf("\nstr is %s",str);
while((ch = str[i++] )!= '\0')
{
j = i;
printf("\n----ch = %c----",ch);
while(str[j] != '\0')
{
printf("\n--------Checking whether %c = %c \n",str[j],ch);
if(ch == str[j])
{
printf("\n------------Yes");
while(str[j]!='\0')
{
printf("\nRemoving %c %d -- \n",str[j]);
str[j] = str[++j];
--i;
}
break;
}
printf("\n------------No");
//printf("\njj");
j++;
}
}
return str;
}
You are passing a string literal, which you are not allowed to modify to this function, instead you should do:
char myStr[] = "heee";
removeDuplicate(myStr);
Also, please note that in the following lines your have to specifiers inside the printf (%c %d), but you pass only one argument (str[j]):
printf("\nRemoving %c %d -- \n",str[j]);
This may cause all sorts of bad things...
You should correct your code as follows:
In first while loop: j = i+1;
In third while loop: i--; // is not required
Remove that unwanted specifier form printf("Removing %d %d:",str[j])
Doing incorrectly :
str[j] = str[++j] // you are increasing j before assigning
str[j] = str[j++] // correct way to do.But it is compiler dependent i guess
Better to use:
t = j;
str[t] = str[++j];
I don't think this function does what you want. The remove loop is really fishy.. you decrement i which looks wrong.. and you increment j which is probably also wrong:
while(str[j]!='\0')
{
printf("\nRemoving %c %d -- \n",str[j]);
str[j] = str[++j]; // now the new character is at location j, but since
// you incremented j you can't access it anymore
--i; // why is i dependent on the remove stuff?
}
I would go for a simpler approach. Create a large bool array. Loop through your string and store whether you already encountered the current character or not. If not, print it.
Check the following code :
char* removeDuplicate(char str[])//remove duplicate characters from a string,so that each character in a string is not repeating
{
int i = 0,j;
char ch;
int repIndex=0;
int temp=0;
printf("\nstr is %s",str);
while((ch = str[i++] )!= '\0')
{
j = i;
printf("\n----ch = %c----",ch);
while(str[j] != '\0')
{
printf("\n--------Checking whether %c = %c \n",str[j],ch);
repIndex = j;
if(ch == str[repIndex])
{
printf("\n------------Yes");
while(str[repIndex]!='\0')
{
printf("\nRemoving %c %d \n",str[j]);
temp = repIndex;
str[temp] = str[++repIndex];
}
} else { j++; }
}
}
return str;
}
int main ( int argc, char ** argv)
{
char myStr[]="asdfhelllasdfloofdoeohz";
printf ("OUtput is : %s \n", removeDuplicate(myStr) );
}
//removing the redundant characters in a string
#include<stdio.h>
int main()
{
int i=0,j,arr[26]={},temp; //array for hashing
char s[10],arr1[10],*p; //array 4 storing d output string
printf("Enter the string\n");
scanf("%s",s);
p=s;
while(*p!='\0')
{
temp=((*p)>92)?(*p)-'a':(*p)-'A'; //asuming lowr and upr letters are same
if(arr[temp]==0) //if it is not hashed ie if that char is not repeated
{
arr1[i]=temp+'a'; //return the string in lowecase
arr[temp]=1; //storing value so that this character sd not be placed again
i++;
}
p++; //else ignore the alphabet
}
for(j=0;j<i;j++)
{
printf("%c",arr1[j]); //print the string stored in arr1
}
return 0;
}
I have corrected the code as follows
char* removeDuplicate(char str[])//remove duplicate characters from a string,so that each character in a string is not repeating
{
int i = 0,j;
char ch;
while((ch = str[i++] )!= '\0')
{
j = i;
while(str[j] != '\0')
{
if(ch == str[j])
{
while(str[j]!='\0')
str[j] = str[++j];
i--;
break;
}
j++;
}
}
return str;
}
#include<iostream.h>
#include<conio.h>
#include<stdio.h>
#include<string.h>
void main()
{
clrscr();
char *str;
int count=0;
cout<<"enter the string which have repetative characters"<<endl;
cin>>str;
char *str2;
int m=0;
for(int i=0;i<=strlen(str);i++)
{
char ch=str[i];
if(i==0)
{
str2[m]=str[i];
m++;
}
for(int j=0;j<=strlen(str2);j++)
{
if(ch==str2[j])
count++;
}
if(count==0)
{
str2[m]=str[i];
m++;
}
count=0;
if(i==strlen(str))
str2[m]='\0';
}
puts(str2);
getch();
}
O(n) complexity
char *removeDuplicates(char *str){
int hash[256] = {0};
int currentIndex = 0;
int lastUniqueIndex = 0;
while(*(str+currentIndex)){
char temp = *(str+currentIndex);
if(0 == hash[temp]){
hash[temp] = 1;
*(str+lastUniqueIndex) = temp;
lastUniqueIndex++;
}
currentIndex++;
}
*(str+lastUniqueIndex) = '\0';
return str;
}
Refer: http://www.geeksforgeeks.org/remove-all-duplicates-from-the-input-string/