ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

C program to delete duplicate words in the string

Here, we are going to learn how to delete duplicate words in the string in C programming language?
Submitted by Nidhi, on July 17, 2021

Problem Solution:

Read a string from the user then delete duplicate words from the string using C program.

Program:

The source code to delete duplicate words in the string is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to delete duplicate words in string

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main()
{

    char str[64];
    char words[6][16];

    int i = 0;
    int j = 0;
    int k = 0;
    int l = 0;

    printf("Enter string: ");
    scanf("%[^\n]s", str);

    while (str[i] != 0) {
        if (str[i] == ' ') {
            words[k][j] = '\0';
            k++;
            j = 0;
        }
        else {
            words[k][j] = str[i];
            j++;
        }
        i++;
    }
    words[k][j] = '\0';

    j = 0;
    for (i = 0; i < k; i++) {
        int present = 0;
        for (l = 1; l < k + 1; l++) {
            if (words[l][j] == '\0' || l == i)
                continue;

            if (strcmp(words[i], words[l]) == 0) {
                words[l][j] = '\0';
                present = present + 1;
            }
        }
    }

    j = 0;
    printf("Result is:\n");
    for (i = 0; i < k + 1; i++) {
        if (words[i][j] == 0)
            continue;
        else
            printf("%s ", words[i]);
    }
    printf("\n");

    return 0;
}

Output:

RUN 1:
Enter string: Hello Hello World
Result is:
Hello World 

RUN 2:
Enter string: This is is my Laptop Laptop
Result is:
This is my Laptop 

RUN 3:
Enter string: Hello, World!
Result is:
Hello, World! 

Explanation:

In the main() function, we created a string str and read the value of str from the user. Then we removed the duplicate words from the string and printed the result on the console screen.

C String Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.