In these programs, we use for loop and if statement to find the number of unique characters but in python, we use the set function to find unique characters, set is a collection of unique elements there is no duplicate elements.
Here is an example:
Code in C Language:
#include <stdio.h>
#include <string.h>
int main()
{
char input[50]="apple";
int i, j, count=0;
int n = strlen(input);
for(i=0; i<n; i++){
int flag=0;
for(j=0; j<i; j++){
if(input[i]==input[j]){
flag=1;
break;
}
}
if(flag==0){
count++;
}
}
printf("%d",count);
return 0;
}
Output:
4
Code in C++:
#include <iostream>
using namespace std;
int main()
{
string input = "where";
int i,j,count=0;
// cin>>input;
int n = input.length();
for(i=0; i<n; i++){
int flag=0;
for(j=0; j<i; j++){
if(input[i]==input[j]){
flag=1;
break;
}
}
if(flag==0){
count++;
}
}
std::cout << count << std::endl;
return 0;
}
Output:
4
Code in Java:
public class Main
{
public static void main(String[] args) {
String input = "madam";
int i,j,count=0;
char arr[]=input.toCharArray();
int n = arr.length;
for(i=0; i<n; i++){
int flag=0;
for(j=0; j<i; j++){
if(arr[i]==arr[j]){
flag=1;
break;
}
}
if(flag==0){
count++;
}
}
System.out.println(count);
}
}
Output:
3
Code in Python
str = "session"
uniqueStr = set(str)
print(len(uniqueStr))
Output:
5
0 Comments