Click here to Skip to main content
16,020,459 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hii...
Pls find me the soln to find most char appear in a given string...in javascript or c#
i've tried in javascript but strucked pls get me soln...
C#
function FindMostCharInStr(x)
    {
        var len=x.value.length;
        var chars=new Array(len);
        var CharRepeatMostTimes;
        for (var i=0;i<len;i++)
        {
            chars=x.value.charAt(i);
        }
        for(var j=0;j<chars.length;j++)
        {
            if(chars[j]==chars[j+1])
            {
                CharRepeatMostTimes++;
            }
        }
        alert(CharRepeatMostTimes);
Posted
Comments
nagendrathecoder 10-Apr-12 6:16am    
Where you got struck? Are you getting any error?

Solution 5 by Andreas Gieriet is very good. I voted 5.
This is an alternative using System.Text.RegularExpressions.Regex class
C#
using System.Text.RegularExpressions;
void Main()
{
	//Maximum number of Consecutive occurances of a character
	string inputText = "hhbvnnvbmvmvmvbffffffffmmffffff"; 
	string maxConOcc = GetMaxOccuredChars(inputText);
	if (!string.IsNullOrEmpty(maxConOcc))
		Console.WriteLine ("Max consecutive occurances:\n--char: {0} Occurances: {1}",
			maxConOcc[0],maxConOcc.Length);
	//Maximum number of total occurances of a character		
	string sortedInputText = new string(inputText.ToCharArray().OrderBy(ch => ch).ToArray());
	string maxOccuredChar = GetMaxOccuredChars(sortedInputText);
	if (!string.IsNullOrEmpty(maxOccuredChar))
		Console.WriteLine ("Max Total occurances:\n--char: {0} Occurances: {1}",
			maxOccuredChar[0],maxOccuredChar.Length);
}

// Define other methods and classes here
public static string GetMaxOccuredChars(string inputText){
//(?<ls>(?<let>.)\k<let>*) matches only the character followed by the same character zero or more times
	MatchCollection matches = Regex.Matches(inputText,@"(?<ls>(?<let>.)\k<let>*)");
	//Maximum number of consecutive occurances of a character
	string maxConOcc = string.Empty;
	foreach(Match match in matches)
		if (match.Groups[1].Value.Length > maxConOcc.Length) 
			maxConOcc =  match.Groups[1].Value;
	return maxConOcc;
}
//output from the above code
//Max consecutive occurances:
//--char: f Occurances: 8
//Max Total occurances:
//--char: f Occurances: 14
 
Share this answer
 
v3
Comments
Member 10237629 2-Jul-14 4:21am    
Unable to use this regular expreesion in java
Is it possible ?
If you need the character with most instances in a string (versus the longest sequence of the same character), then the following C# code may help:
C#
string text = "hhbvnnvbmvmvmvbffffffffmmffffff";

Dictionary<char, int> bins = new Dictionary<char, int>();
char max = text.Aggregate(text[0], (a, c) => {
    if (bins.ContainsKey(c)) bins[c]++; else bins.Add(c, 1);
    return bins[a] < bins[c] ? c : a;
});

Console.WriteLine("{0} = {1} occurances", max, bins[max]);


Cheers
Andi
 
Share this answer
 
Comments
VJ Reddy 10-Apr-12 11:54am    
Succinct and nice answer. +5
Andreas Gieriet 10-Apr-12 15:12pm    
Thanks, VJ!
JavaScript
<script language="javascript" type="text/javascript">
    
    function FindMostCharInStr()
    {        
        var  x="ashish";
      //  var len = x.length;        
        var chars= new Array(x.length);
        var count= new Array(x.length);
       // alert(chars);
        var CharRepeatMostTimes;
        for (var i=0;i<x.length;i++)>
        {
            chars[i] = x.charAt(i);
        
        }
        for (var i=0;i<x.length;i++)>
        {
            count[i] =1;
        
        }
        for(var j=0;j<chars.length;j++)>
        {
             for(var k=j+1;k<chars.length;k++)>
             {
                if(chars[j]==chars[k])
                {   
                  //  alert(chars[j]);
                    count[j]++;
                }
             }               
          alert(chars[j] +'--'+ count[j]);
        }
     }
    </script>
 
Share this answer
 
Comments
Nelek 10-Apr-12 14:41pm    
Copied from an OP's "answer" (spelling a bit corrected)
Hi Ashish, have you worked in your system here? I can't find the solution.
I am calling this jScript function on: OnChange="return FindMostCharInStr()"
AshishChaudha 11-Apr-12 0:19am    
yes I worked on my system..I called the function on : onClick="FindMostCharInStr();"
Hi,

Please Check Below code

C#
protected void CharRepeatMostTimes()
        {
            String strValue="AAAAAAAAAMMMOL";
            Int32 len=strValue.Length;
            Char [] chars=strValue.ToCharArray();
            List<Char> charList = new List<Char>();
            for (Int32 j = 0; j < chars.Length; j++)
            {
                if (!charList.Contains(chars[j]))
                    charList.Add(chars[j]);
            }
            foreach (Char c in charList)
            {
                Int32 count = CountChar(strValue, c);
                MessageLabel.Text = MessageLabel.Text + String.Format("Char '{0}' Occurce '{1}' times" , c, count);
            }
        }
        public int CountChar(string input, char c)
        {
            int retval = 0;
            for (int i = 0; i < input.Length; i++)
                if (c == input[i])
                    retval++;
            return retval;
        }


Thanks
Amol K Gunjal
 
Share this answer
 
Try this but in C#
C#
string text = "hhbvnnvbmvmvmvbffffffffffffff";
           text = text.ToUpper();
           Int16 [] ii=new Int16[100];
           Char[] cc=new Char[100];
           Char ccc='\0';
           Int16 iii=0;
          // int iiii=0;
           for (Int16 i = 0; i < text.Length; i++)
           {

               if (text[i] != ' ' && (i == 0 || !text.Substring(0, i - 1).Contains(text[i])))
               {
                   if (CountCharacters(text[i], text)>=iii)
                   {
                       //ii[i] = CountCharacters(text[i], text);
                       //cc[i] = text[i];
                       iii = CountCharacters(text[i], text);
                       ccc = text[i];
                   }
               }
           }


           MessageBox.Show("The char "+ccc+" find maximum "+iii+" times");
       }

       protected Int16 CountCharacters(char target, string text)
       {

           Int16 returnVal = 0;

           for (Int16 i = 0; i < text.Length; i++)
           {
               if (text[i].ToString().ToUpper() == target.ToString().ToUpper())
                   returnVal++;
           }
           return returnVal;
       }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900