
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
Convert given string so that it holds only distinct characters in C++
In this tutorial, we will be discussing a program to convert given string so that it holds only distinct characters.
For this we will be provided with a string. Our task is to traverse through the string and replace all the recurring characters with any random characters that are not already present into the string.
Example
#include<bits/stdc++.h> using namespace std; //collecting the distinct characters //in the string int calculate_zero(int i, int occurrences[]){ while (i < 26) { //if it is present only once if (occurrences[i] == 0) return i; i++; } //if all are doubles or more return -1; } //printing the modified string string print_modified(string str) { int n = str.length(); //if conversion //not possible if (n > 26) return "-1"; string ch = str; int i, occurrences[26] = {0}; //counting the occurrences for (i = 0; i < n; i++) occurrences[ch[i] - 'a']++; int index = calculate_zero(0, occurrences); for (i = 0; i < n; i++) { //replacing the character if (occurrences[ch[i] - 'a'] > 1) { occurrences[ch[i] - 'a']--; ch[i] = (char)('a' + index); occurrences[index] = 1; //moving to the next character index = calculate_zero(index + 1, occurrences); } } cout << ch << endl; } int main() { string str = "tutorialspoint"; print_modified(str); }
Output
bucdrealspoint
- Related Articles
- Extract only characters from given string in Python
- Find distinct characters in distinct substrings of a string
- Convert a given Binary tree to a tree that holds Logical AND property on C++
- Print all distinct characters of a string in order in C++
- Longest string with two distinct characters in JavaScript
- Counting substrings of a string that contains only one distinct letter in JavaScript
- Convert characters of a string to opposite case in C++
- Convert an arbitrary Binary Tree to a tree that holds Children Sum Property in C++
- C Program to delete n characters in a given string
- Sorting contents of a string that holds integer values in Java
- Convert the string into palindrome string by changing only one character in C++
- Convert List of Characters to String in Java
- How to convert a list of characters into a string in C#?
- How to convert an array of characters into a string in C#?
- Convert a String into a square matrix grid of characters in C++

Advertisements