Hi Nishant,
Check the code below.
<script language="javascript" type="text/javascript">
function unique()
{
// Step 1: total ASCII characters=256, so take array of size 256, from 0-255, first time fill all positions with '0'
// The Array object is used to store multiple values in a single variable. Here i m defining array size to 256, i.e. 0 - 255
a = new Array(255);
count=0; // take one count variable, initialize that too 0.
k=0; // same
str = document.form1.txt1.value; // string to check. Taking user input from form.
for(i=0 ; i<255 ; i++) // start looping from 0-255
{
a[i]=0; // for a first time make all array positions to zero.
}
// Step 2: whenever any character comes, i am incrementing its ASCII position.
for(i=0 ; i<str.length ; i++) // loop to inputted strings length
{
k=str.charCodeAt(i); // charCodeAt() - Returns the Unicode(ASCII) of the character at the specified index
a[k]++; // Increment that position value.
}
//The concept behind this is, if a same character comes twice, it will increment its position value by '1'.. So finally we need to fetch the array position value character using fromCharCode() method( i. e. whose value is 1). Simple logic.
// Step 3: Checking which position is equal to '1' and then fetch corresponding ASCII character.
for(i=0 ; i<255 ; i++) // loop from 0 - 255
{
if(a[i] == 1) // fetch array value equal to value..
{
document.write(String.fromCharCode(i)+" "); // fromCharCode() - Converts Unicode values to characters at the specified index.
count++; // Increment the count variable. This will tell no. of unique characters in a string.
}
}
document.write("<br />Total Number Of Unique Letters In A String = "+count); // Print the value.
}
</script>
Sep 3, 2010