Array of Characters - java

The Following method receives an array of Character objects and returns a new array with only characters that are digits.
Example;
old[] array:{1,R,Y,O,2,3,3 }----new [] array: {1,2,3,3}.
This is my code, and it is not returning what I want it to return.
public static char[] getDigits(char[] charArray) {

I think you need to do two loops to size your array correctly.
public static char[] getDigits(char[] charArray) {
int digitCount = 0;
for (char ch : charArray) {
if (Character.isDigit(ch)) {
digitCount++;
}
}
char[] toReturnDigits = new char[digitCount];
int index = 0;
for (char ch : charArray) {
if (Character.isDigit(ch)) {
toReturnDigits[index++] = ch;
}
}
return toReturnDigits;
}
public static char[] getDigitsOld(char[] charArray) {
int arrayLength = charArray.length;
char[] toReturnDigits = new char[arrayLength];
int index = 0;
for (int i = 0; i < arrayLength; i++) {
if (charArray[i] >= 48 && charArray[i] <= 57) {
toReturnDigits[index++] = charArray[i];
}
}
return toReturnDigits;
}
public static void main(String arg[]) {
char[] old = new char[] { '1', 'R', 'Y', 'O', '2',
'3', '3' };
System.out.println(Arrays
.toString(getDigitsOld(old)));
System.out.println(Arrays
.toString(getDigits(old)));
}
Outputs
[1, 2, 3, 3,
[1, 2, 3, 3]

Why not just checking if is a number?:
public static char[] getDigits(char[] charArray) {
int arrayLength = charArray.length;
char[] toReturnDigits = new char[arrayLength];
int index = 0;
for (int i = 0; i < arrayLength; i++) {
if (parseInt(charArray[i].toString(), 10)) { //assuming you expect base 10 digits
toReturnDigits[index++] = charArray[i];
}
}
return toReturnDigits;
}
EDIT: To solve the issue with the array length you could use a dynamic array instead of preallocating it:
...
var toReturnDigits = [];
for (int i = 0; i < arrayLength; i++) {
if (parseInt(charArray[i].toString(), 10)) { //assuming you expect base 10 digits
toReturnDigits.push(charArray[i]);
}
}
return toReturnDigits;

If you want to array to just contain the digits, you either have to count the number of digits before you create the array or use a list.
P.S. You should prefer to use Character.isDigit(char) as opposed to comparing.

Perhaps you could try something like:
public static char[] getDigits(final char[] array){
final StringBuilder builder = new StringBuilder();
for(final char c : array)
if(Character.isDigit(c))
builder.append(c);
return builder.toString().toCharArray();
}

You can do this using regex easily.
public static char[] getDigits(char[] charArray) {
Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher(String.valueOf(charArray));
String str=new String();
while (m.find()) {
str=str+m.group();
}
return str.toCharArray();
}
Demo
Again you can do this easy in following way too.
public static char[] getDigits(char[] charArray) {
String str=new String();
for(int i=0;i<charArray.length;i++){
if(Character.isDigit(charArray[i])){
str=str+charArray[i];
}
}
return str.toCharArray();
}

Related

Logic Correction for reverse words input-[ Tom Cat ] O/p [Cat Tom] without using split function

public static void reverse() {
int x=0;
char temp = 0;
String toStrore;
char checkSpace=' ';
System.out.println("Enter a line to reverse");
Scanner sc=new Scanner(System.in);
String userInput=sc.nextLine();
char[] charArray=userInput.toCharArray();
for(int i=charArray.length-1;i>=0;i--){
char tchar=charArray[i];
while(tchar==checkSpace){
x = ++i;
for(int j=x;j<=charArray.length-1;i++){
temp=(char) (temp+charArray[j]);
System.out.print(temp);
}
}
}
}
Please help me with logic.
NOTE: I DONT WANT TO USE ANY INBUILT FUNCTION EXCEPT lenght().
Here something, but you have to at least use String.charAt() and String.length(). The string is reversed by searching backwards until you find a space. Then it appends what's after the space until it reaches the end of the string or finds another space. Lastly, the first word will get added to the result.
public class MyClass {
public static void main(String args[]) {
System.out.println(reverse("The quick brown fox jumps over the lazy dog"));
}
private static String reverse(String data) {
String result = "";
// Build the string in reverse as you find spaces
for (int i = data.length() - 1; i > -1; i--) {
if (data.charAt(i) == ' ') {
int j = i + 1;
while (j < data.length() && data.charAt(j) != ' ') {
result += data.charAt(j++);
}
result += " ";
}
}
// Add the first word to the result
int i = 0;
while (i < data.length() && data.charAt(i) != ' ') {
result += data.charAt(i++);
}
return result;
}
}
Result
dog lazy the over jumps fox brown quick The
try out this one
import java.util.Arrays;
public class Reverse {
public static void main(String... args) {
getReversed("Tom Cat");
}
public static void getReversed(String str) {
char[] arr = str.toCharArray();
int len = 0;
for (char ch : arr) {
if (ch == ' ') {
len++;
}
}
String[] res = new String[len + 1];
int start = 0;
int idx = len;
while (idx > -1) {
StringBuilder builder = new StringBuilder();
for (int i = start; i < arr.length; i++) {
if (arr[i] != ' ') {
builder.append(arr[i]);
if (i == arr.length - 1) {
res[idx--] = builder.toString();
}
} else {
res[idx--] = builder.toString();
builder.setLength(0);
start = i;
}
}
}
System.out.println(Arrays.toString(res));
}
}
Updated optimized code
public static void main(String... args) {
String str = "Cat Tom";
char[] charArr = str.toCharArray();
int len = charArr.length;
ArrayList<String> list = new ArrayList<>();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < len; i++) {
char ch = charArr[i];
if (ch == ' ') {
list.add(stringBuilder.toString());
stringBuilder = new StringBuilder();
} else if (i == len - 1) {
list.add(stringBuilder.append(ch).toString());
} else {
stringBuilder.append(ch);
}
}
Collections.reverse(list);
System.out.println(list);
}
Output
[Cat, Tom]

Compare two Arrays and remove duplicates from Original Array java(no lists)

So I am trying to compare two char arrays, and all letters that are present in keyW, should be removed from the array invAlphabet. I have been able to find the duplicates inside the invAlphabet array, however, I don't know how to remove the duplicate elements without using Lists or Collections which I should not use...
Any idea?
public static void main(String[] args)
{
final int SIZE = 26;
char[] keyW = {'A', 'L','O'};
char[] invAlphabet = new char [SIZE];
for (int i = 0; i < SIZE; i++)
{
invAlphabet[i] = (char)('Z' - i);
}
for (int i = 0; i<keyW.length; i++)
{
for (int j = 0; j < invAlphabet.length; j++)
{
if(keyW[i] == invAlphabet[j])
{
//need to delete the invAlphabet[j] elements that are duplicates
System.out.println(invAlphabet[j]);
System.out.println(j);
break;
}
}
}
}
If you want to solve it in O(n), then you can mark all the character That are present in keyW[] array, and then check and don't add them to your new noDuplicateArray[].
char[] keyW = {'A', 'L', 'O', 'P'};
char[] invAlphabet = {'X', 'A', 'P', 'B', 'C'};
//create boolean array
boolean[] mark = new boolean[128];
Arrays.fill(mark, false);
//mark which characters are present in keyW array
for (char ch : keyW) {
mark[ch] = true;
}
// find number of duplicate character in invAlphabet array
int duplicateCount = 0;
for (char ch : invAlphabet) {
if (mark[ch]) {
duplicateCount++;
}
}
// create new array
// size of new array = invAlphabet array length - duplicate number of character in invAlphabet array
char[] noDuplicateArray = new char[invAlphabet.length - duplicateCount];
//add character in new array
int idx = 0;
for (char ch : invAlphabet) {
if (!mark[ch]) {
noDuplicateArray[idx++] = ch;
}
}
You cannot resize the array object, as you see you could use some other data types. However, if you are allowed to just use array, you can put some other non-alphabetic character in place of removed character. For example '0'. So while using or printing you can skip the character in the array if it is '0'.
Could you use String and replace method?
String invAlphabetString = new String(invAlphabet);
for(char i:keyW){
invAlphabetString=invAlphabetString.replace(""+i, "");
}
char[] invAlphabetWithoutKeyW = invAlphabetString.toCharArray();
System.out.println(Arrays.toString(invAlphabetWithoutKeyW));
I would begin by writing a method to search a char[] for a given char (that is, a contains method) like
private static boolean contains(char[] chars, char ch) {
for (char c : chars) {
if (c == ch) {
return true;
}
}
return false;
}
Then the problem can be decomposed into two steps. First, count the duplicates and second build an output array by copying without the duplicates. Something like
int dupes = 0;
for (char ch : invAlphabet) {
if (contains(keyW, ch)) {
dupes++;
}
}
int i = 0;
char[] noDupes = new char[invAlphabet.length - dupes];
for (char ch : invAlphabet) {
if (!contains(keyW, ch)) {
noDupes[i] = ch;
i++;
}
}
Alternatively, you could convert your keyW array to a String. And, in Java 8+, you could construct a Stream of your characters. Map to the array, filter against the String and then collect to another String. Something like,
String keyWord = new String(keyW);
char[] noDupes = IntStream.range(0, invAlphabet.length)
.mapToObj(x -> invAlphabet[x])
.filter(ch -> (keyWord.indexOf(ch) < 0))
.map(String::valueOf)
.collect(Collectors.joining()).toCharArray();

How to convert an array of bits into text

I had a string for eg "java education" which I have converted into bits. Now I have an array of bits. I want to convert it back into text. How to do this?
String s="Java Education";
char[] ch=s.toCharArray();
String g=" ";
StringBuilder sb= new StringBuilder();
for(char c:ch)
{
g=Integer.toBinaryString((int)c);
sb.append(ch);
}
char[] ch2= sb.toString.toCharArray();
I want to get back the text from the array ch2.
Try this
import java.util.Arrays;
public class DecodeBits {
public static void main(String[] args) {
String s = "Java Education";
char[] ch = s.toCharArray();
StringBuilder sb = new StringBuilder();
for (char c : ch) {
// Wen need a fix length
String g = String.format("%16s", Integer.toBinaryString((int) c)).replace(' ', '0');
// this seems to be typo
// sb.append(ch);
sb.append(g);
}
char[] ch2 = sb.toString().toCharArray();
int start = 0;
while (start < ch2.length - 15) {
char[] bits = Arrays.copyOfRange(ch2, start, start + 16);
int cValue = Integer.parseInt(new String(bits), 2);
char[] chars = Character.toChars(cValue);
System.out.print(chars[0]);
start += 16;
}
System.out.println("");
}
}
Here is my implementation:
String s="Java Education";
char[] ch=s.toCharArray();
String g="";
StringBuilder sb= new StringBuilder();
for(char c:ch)
{
g=Integer.toBinaryString((int)c);
if(g.length()<8){
for(int h=0; h<8-g.length(); h++){
g="0"+g;
}
}
sb.append(g);
sb.append(',');
}
char[] ch2= sb.toString().toCharArray();
String[] s3 = new String(ch2).split(",");
for(String t: s3){
String d="";
for(int x=t.length()-1; x>=0; x--) d+=t.charAt(x);
t=d;
int num=0;
for(int j=0; j<t.length(); j++){
num+=Integer.parseInt(""+t.charAt(j))*Math.pow(2, j);
}
System.out.print((char)num);
}

Converting \n to String without \\n

How can I convert "\n" into a char[]? I want to do this because I want to do some string manipulation when \n is entered in the method as input. I know that if \\n is entered then the output will be \n as a string. I want to implement a method to take in input as \n not \\n to get the string result.
tests:
char[] arr = new char[2];
String str = "\n";
arr = str.toCharArray();
System.out.println(arr.length);
for (char c : arr) {
System.out.println(c);
}
ouput:
1
// newline empty space
my reverse string method
public static String reverseStr(String str) {
if ( str == null ) {
return null;
}
int len = str.length();
if (len <= 0) {
return "";
}
char[] strArr = new char[len];
int count = 0;
for (int i = len - 1; i >= 0; i--) {
strArr[count] = str.charAt(i);
count++;
}
return new String(strArr);
}
newlines are represented as 10 in ascii. you can try this.
char[] arr = new char[3];
int str = 10;
arr[0] = 'a';
arr[1] = (char)str;
arr[2] = 'c';
System.out.println(arr.length);
for (char c : arr) {
System.out.println(c);
}
One way to do it is by using Stringbuilder
String builder(StringBuilder has overloaded methods for char and Sting).
StringBuilder str= new StringBuilder();
str.append('\n'); or
str.append("\n");

How to find the most frequently occurring character in a string with Java?

Given a paragraph as input, find the most frequently occurring character. Note that the case of the character does not matter. If more than one character has the same maximum occurring frequency, return all of them
I was trying this question but I ended up with nothing. Following is the code that I tried but it has many errors I am unable to correct:
public class MaximumOccuringChar {
static String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
public static void main(String[] args)
{
MaximumOccuringChar test = new MaximumOccuringChar();
char[] result = test.maximumOccuringChar(testcase1);
System.out.println(result);
}
public char[] maximumOccuringChar(String str)
{
int temp = 0;
int count = 0;
int current = 0;
char[] maxchar = new char[str.length()];
for (int i = 0; i < str.length(); i++)
{
char ch = str.charAt(i);
for (int j = i + 1; j < str.length(); j++)
{
char ch1 = str.charAt(j);
if (ch != ch1)
{
count++;
}
}
if (count > temp)
{
temp = count;
maxchar[current] = ch;
current++;
}
}
return maxchar;
}
}
You already got your answer here: https://stackoverflow.com/a/21749133/1661864
It's a most easy way I can imagine.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MaximumOccurringChar {
static final String TEST_CASE_1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today. Help!";
public static void main(String[] args) {
MaximumOccurringChar test = new MaximumOccurringChar();
List<Character> result = test.maximumOccurringChars(TEST_CASE_1, true);
System.out.println(result);
}
public List<Character> maximumOccurringChars(String str) {
return maximumOccurringChars(str, false);
}
// set skipSpaces true if you want to skip spaces
public List<Character> maximumOccurringChars(String str, Boolean skipSpaces) {
Map<Character, Integer> map = new HashMap<>();
List<Character> occurrences = new ArrayList<>();
int maxOccurring = 0;
// creates map of all characters
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (skipSpaces && ch == ' ') // skips spaces if needed
continue;
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
if (map.get(ch) > maxOccurring) {
maxOccurring = map.get(ch); // saves max occurring
}
}
// finds all characters with maxOccurring and adds it to occurrences List
for (Map.Entry<Character, Integer> entry : map.entrySet()) {
if (entry.getValue() == maxOccurring) {
occurrences.add(entry.getKey());
}
}
return occurrences;
}
}
Why don't you simply use N letter buckets (N=number of letters in alphabet) ? Just go along the string and increment the corresponding letter bucket. Time complexity O(n), space complexity O(N)
This method allows you to find the most frequently occurring character in a string:
public char maximumOccuringChar(String str) {
return str.chars()
.mapToObj(x -> (char) x) // box to Character
.collect(groupingBy(x -> x, counting())) // collect to Map<Character, Long>
.entrySet().stream()
.max(comparingByValue()) // find entry with largest count
.get() // or throw if source string is empty
.getKey();
}
import java.util.Scanner;
public class MaximumOccurringChar{
static String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
public static void main(String[] args) {
MaximumOccurringChar test = new MaximumOccurringChar();
String result = test.maximumOccuringChar(testcase1);
System.out.println(result);
}
public String maximumOccuringChar(String str) {
int temp = 0;
int count = 0;
int current = 0;
int ind = 0;
char[] arrayChar = {'a','b' , 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'};
int[] numChar = new int[26];
char ch;
String s="";
str = str.toLowerCase();
for (int i = 0; i < 26; i++) {
count = 0;
for (int j = 0; j < str.length(); j++) {
ch = str.charAt(j);
if (arrayChar[i] == ch) {
count++;
}
}
numChar[i] = count++;
}
temp = numChar[0];
for (int i = 1; i < numChar.length; i++) {
if (temp < numChar[i]) {
temp = numChar[i];
ind = i;
break;
}
}
System.out.println(numChar.toString());
for(int c=0;c<26;c++)
{
if(numChar[c]==temp)
s+=arrayChar[c]+" ";
}
return s;
}
}
Algorithm:-
Copying the String character by character to LinkedHashMap.
If its a new character then insert new character , 1.
If character is already present in the LinkedHashMap then update the value by incrementing by 1.
Iterating over the entry one by one and storing it in a Entry object.
If value of key stored in entry object is greater than or equal to current entry then do nothing
Else, store new entry in the Entry object
After looping through, simply print the key and value from Entry object.
public class Characterop {
public void maxOccur(String ip)
{
LinkedHashMap<Character, Integer> hash = new LinkedHashMap();
for(int i = 0; i<ip.length();i++)
{
char ch = ip.charAt(i);
if(hash.containsKey(ch))
{
hash.put(ch, (hash.get(ch)+1));
}
else
{
hash.put(ch, 1);
}
}
//Set set = hash.entrySet();
Entry<Character, Integer> maxEntry = null;
for(Entry<Character,Integer> entry : hash.entrySet())
{
if(maxEntry == null)
{
maxEntry = entry;
}
else if(maxEntry.getValue() < entry.getValue())
{
maxEntry = entry;
}
}
System.out.println(maxEntry.getKey());
}
public static void main(String[] args) {
Characterop op = new Characterop();
op.maxOccur("AABBBCCCCDDDDDDDDDD");
}
}
The Big O below solution is just o(n). Please share your opinion on it.
public class MaxOccuringCahrsInStr {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String str = "This is Sarthak Gupta";
printMaxOccuringChars(str);
}
static void printMaxOccuringChars(String str) {
char[] arr = str.toCharArray();
/* Assuming all characters are ascii */
int[] arr1 = new int[256];
int maxoccuring = 0;
for (int i = 0; i < arr.length; i++) {
if (arr[i] != ' ') { // ignoring space
int val = (int) arr[i];
arr1[val]++;
if (arr1[val] > maxoccuring) {
maxoccuring = arr1[val];
}
}
}
for (int k = 0; k < arr1.length; k++) {
if (maxoccuring == arr1[k]) {
char c = (char) k;
System.out.print(c + " ");
}
}
}
}
function countString(ss)
{
var maxChar='';
var maxCount=0;
for(var i=0;i<ss.length;i++)
{
var charCount=0;
var localChar=''
for(var j=i+1;j<ss.length;j++)
{
if(ss[i]!=' ' && ss[i] !=maxChar)
if(ss[i]==ss[j])
{
localChar=ss[i];
++charCount;
}
}
if(charCount>maxCount)
{
maxCount=charCount;
maxChar=localChar;
}
}
alert(maxCount+""+maxChar)
}
Another way to solve it. A simpler one.
public static void main(String[] args) {
String str= "aaaaaaaaaaaaaaaaabbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbcddddeeeeee";
String str1 = "dbc";
if(highestOccuredChar(str) != ' ')
System.out.println("Most Frequently occured Character ==> " +Character.toString(highestOccuredChar(str)));
else
System.out.println("The String doesn't have any character whose occurance is more than 1");
}
private static char highestOccuredChar(String str) {
int [] count = new int [256];
for ( int i=0 ;i<str.length() ; i++){
count[str.charAt(i)]++;
}
int max = -1 ;
char result = ' ' ;
for(int j =0 ;j<str.length() ; j++){
if(max < count[str.charAt(j)] && count[str.charAt(j)] > 1) {
max = count[str.charAt(j)];
result = str.charAt(j);
}
}
return result;
}
public void countOccurrence(String str){
int length = str.length();
char[] arr = str.toCharArray();
HashMap<Character, Integer> map = new HashMap<>();
int max = 0;
for (char ch : arr) {
if(ch == ' '){
continue;
}
if (map.containsKey(ch)) {
map.put(ch, map.get(ch) + 1);
} else {
map.put(ch, 1);
}
}
Set<Character> set = map.keySet();
for (char c : set) {
if (max == 0 || map.get(c) > max) {
max = map.get(c);
}
}
for (Character o : map.keySet()) {
if (map.get(o).equals(max)) {
System.out.println(o);
}
}
System.out.println("");
}
public static void main(String[] args) {
HighestOccurence ho = new HighestOccurence();
ho.countOccurrence("aabbbcde");
}
public void stringMostFrequentCharacter() {
String str = "My string lekdcd dljklskjffslk akdjfjdkjs skdjlaldkjfl;ak adkj;kfjflakj alkj;ljsfo^wiorufoi$*#&$ *******";
char[] chars = str.toCharArray(); //optionally - str.toLowerCase().toCharArray();
int unicodeMaxValue = 65535; // 4 bytes
int[] charCodes = new int[unicodeMaxValue];
for (char c: chars) {
charCodes[(int)c]++;
}
int maxValue = 0;
int maxIndex = 0;
for (int i = 0; i < unicodeMaxValue; i++) {
if (charCodes[i] > maxValue) {
maxValue = charCodes[i];
maxIndex = i;
}
}
char maxChar = (char)maxIndex;
System.out.println("The most frequent character is >" + maxChar + "< - # of times: " + maxValue);
}
For Simple String Manipulation, this program can be done as:
package abc;
import java.io.*;
public class highocc
{
public static void main(String args[])throws IOException
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter any word : ");
String str=in.readLine();
str=str.toLowerCase();
int g=0,count,max=0;;
int ar[]=new int[26];
char ch[]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
for(int i=0;i<ch.length;i++)
{
count=0;
for(int j=0;j<str.length();j++)
{
char ch1=str.charAt(j);
if(ch[i]==ch1)
count++;
}
ar[i]=(int) count;
}
max=ar[0];
for(int j=1;j<26;j++)
{
if(max<ar[j])
{
max=ar[j];
g=j;
}
}
System.out.println("Maximum Occurence is "+max+" of character "+ch[g]);
}
}
Sample Input1: Pratik is a good Programmer
Sample Output1: Maximum Occurence is 3 of character a
Sample Input2: hello WORLD
Sample Output2: Maximum Occurence is 3 of character l
maxOccu m = new maxOccu();
String str = "moinnnnaaooooo";
char[] chars = str.toCharArray();
Arrays.sort(chars);
str = new String(chars);
System.out.println(str);
m.maxOccurence(str);
void maxOccurence(String str) {
char max_char = str.charAt(0),
cur_char,
prev = str.charAt(0);
int cur_count = 0,
max_count = 0,
n;
n = str.length();
for (int i = 0; i < n; i++) {
cur_char = str.charAt(i);
if (cur_char != prev) cur_count = 0;
if (str.charAt(i) == cur_char) {
cur_count++;
}
if (cur_count > max_count) {
max_count = cur_count;
max_char = cur_char;
}
prev = cur_char;
}
System.out.println(max_count + "" + max_char);
}
public class HigestOccurredCharTest {
public static void main(String[] args) {
System.out.println("Enter the char string to check higest occurrence");
Scanner scan = new Scanner(System.in);
String str = scan.next();
if(str != null && !str.isEmpty()){
Map<Character, Integer> map = countOccurrence(str);
getHigestOccurrenceChar(map);
}else{
System.out.println("enter valid string");
}
}
public static Map<Character, Integer> countOccurrence(String str){
char strArr[] = str.toCharArray();
Map<Character, Integer> map = new HashMap<Character , Integer>();
for (Character ch : strArr) {
if(map.containsKey(ch)){
map.put(ch, map.get(ch)+1);
}else{
map.put(ch, 1);
}
}
return map;
}
public static void getHigestOccurrenceChar(Map<Character, Integer> map){
Character ch = null;
Integer no = 0;
Set<Entry<Character, Integer>> entrySet = map.entrySet();
for (Entry<Character, Integer> entry : entrySet) {
if(no != 0 && ch != null){
if(entry.getValue() > no){
no = entry.getValue();
ch = entry.getKey();
}
}else{
no = entry.getValue();
ch = entry.getKey();
}
}
System.out.println(ch+ " Higest occurrence char is "+ no);
}
}
Try Like that:-
string inputString = "COMMECEMENT";
List<Tuple<char, int>> allCharListWithLength = new List<Tuple<char, int>>();
List<char> distinchtCharList = inputString.Select(r => r).Distinct().ToList();
for (int i = 0; i < distinchtCharList.Count; i++)
{
allCharListWithLength.Add(new Tuple<char, int>(distinchtCharList[i], inputString.Where(r => r ==
distinchtCharList[i]).Count()));
}
Tuple<char, int> charWithMaxLength = allCharListWithLength.Where(r => r.Item2 == allCharListWithLength.Max(x => x.Item2)).FirstOrDefault();
Question: Frequently occurring Character in a String
Method 1: Using HashMap
public class t1{
public static void main(String a[]){
Map<Character, Integer> map = new HashMap<>();
String a1 = "GiinnniiiiGiiinnnnnaaaProtijayi";
for(char ch : a1.toCharArray()) {map.put(ch, map.getOrDefault(ch,0)+1);}//for
System.out.println(map);
char maxchar = 0 ;
int maxvalue = Collections.max(map.values());
System.out.println("maxvalue => " + maxvalue);
for( Entry<Character,Integer> entry : map.entrySet()) {
if(entry.getValue() == maxvalue) {
System.out.println("most frequent Character => " + entry.getKey());
}
}//for
}
}
Method 2 : Using count of alphabets in Python
str = "GiinnniiiiGiiinnnnnaaaProtijayi";
count = [0]*256
maxcount= -1
longestcharacter =""
# Traversing through the string and maintaining the count of
# each character
for ch in str:count[ord(ch)] += 1;
for ch in str:
if( maxcount < count[ord(ch)] ):
maxcount = count[ord(ch)]
longestcharacter = ch
print(longestcharacter)
print(maxcount)
IN Java :
public class t1{
public static void main(String[] args) {
String a = "GiinnniiiiGiiinnnnnaaaProtijayi";
int[] count = new int[256];
for (int i = 0; i < a.length(); i++) {
char ch = a.charAt(i);
count[ch] +=1;
}//for
int maxcount = -1 ;
char longest = 0 ;
for( char ch : a.toCharArray()) {
if(count[ch] > maxcount) {
maxcount = count[ch];
longest = ch ;
}//if
}//for
System.out.println(longest);
System.out.println(maxcount);
}//main
}
Method 3: Using collections.Counter().most_common()
import collections
a = "GiinnniiiiGiiinnnnnaaaProtijayi";
fullDictionary = collections.Counter(a).most_common()
FirstElementWithCount = fullDictionary[0]
print(FirstElementWithCount)
FirstElementWithoutCount = FirstElementWithCount[0]
print(FirstElementWithoutCount)
Method 4: Using sorted and key = lambda ch : ch[1]
a = "GiinnniiiiGiiinnnnnaaaProtijayi";
d = {}
for ch in a: d[ch] = d.get(ch, 0) + 1
fullDictionary = sorted(d.items(), key=lambda ch :ch[1], reverse=True)
print(fullDictionary)
FirstElement = fullDictionary[0][0]
print(FirstElement)
package com.practice.ArunS;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class HighestFrequencyElement {
/*
* CONTENTSERV=N(2),T(2),E(2) SearchSort=S(2),r(2)
* HighestFrequencyElement=E(5)
*/
public static void main(String[] args) {
String str = "CONTENTSERV";
findHighestFrequencyElement(str);
}
private static void findHighestFrequencyElement(String str) {
System.out.println("Original String:" + str);
Map<String, Integer> myMap = new TreeMap<String, Integer>();
char[] ch = str.toCharArray();
for (int i = 0; i < str.length(); i++) {
if (myMap.containsKey(Character.toString(ch[i]))) {
Integer value = myMap.get(Character.toString(ch[i]));
myMap.replace(Character.toString(ch[i]), ++value);
} else {
myMap.put(Character.toString(ch[i]), 1);
}
} // end of foor loop
Comparator<Entry<String, Integer>> valueComparator = new Comparator<Entry<String, Integer>>() {
#Override
public int compare(Entry<String, Integer> e1, Entry<String, Integer> e2) {
Integer v1 = e1.getValue();
Integer v2 = e2.getValue();
return v2-v1;
}
};
// Sort method needs a List, so let's first convert Set to List in Java
List<Entry<String, Integer>> listOfEntries = new ArrayList<Entry<String, Integer>>(myMap.entrySet());
// sorting HashMap by values using comparator
Collections.sort(listOfEntries, valueComparator);
for(int i=0;i<listOfEntries.size();i++){
if(listOfEntries.get(0).getValue()==listOfEntries.get(i).getValue()){
System.out.println(listOfEntries.get(i));
}
}
}//end of method
}
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.function.Predicate;
import java.util.stream.Collectors;
public class Answers {
public static void main(String[] args) {
String input1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
String[] arin = input1.split("");
Predicate<String> checkIfValidChar = str -> ((str.charAt(0) >= '0' && str.charAt(0) <= '9')
|| (str.charAt(0) >= 'a' && str.charAt(0) <= 'z')
|| (str.charAt(0) >= 'A' && str.charAt(0) <= 'Z'));
String maxChar = Arrays.stream(arin).max(Comparator.comparing(i -> Arrays.stream(arin).filter(j -> {
return i.equalsIgnoreCase(j) && checkIfValidChar.test(j);
}).count())).get();
int count = Collections.frequency(Arrays.asList(arin), maxChar);
System.out.println(Arrays.stream(arin).filter(i -> {
return Collections.frequency(Arrays.asList(arin), i) == count && checkIfValidChar.test(i);
}).collect(Collectors.toSet()));
}
}
I see many answers that are unnecessarily convoluted, import tons of stuff or use a cannon to shoot a mosquito ( the accepted answer uses an HashTable ).
Here a simple solution:
public List<Character> mostFrequentLetter(String message) {
var m = message
.replaceAll("[^a-z]", "")
.toLowerCase();
int[] count = new int[26];
for(var c : m.toCharArray()){
int i = ((int)c)-97;
count[i]++;
}
var max_i = 0; // index of the most frequent letter
var max_c = count[max_i]; // count of the most frequent letter
var max = new ArrayList<Character>(3); // list containing letters with the same frequency
for(int i = 1; i < 26; ++i){
if (count[i] >= max_c){
max_i = i;
char c = (char)(max_i + 97);
if(count[i]!=max_c){
max.clear();
max_c = count[i];
}
max.add(c);
}
}
return max;
}
Here str will be the given string. This is Javascript code
function maxCharacter(str){
let str1 = str; let reptCharsCount=0; let ele='';let maxCount=0;
let charArr = str1.split('');
for(let i=0; i< str1.length; i++){
reptCharsCount=0;
for(let j=0; j< str1.length; j++){
if(str1[i] === str1[j]) {
reptCharsCount++;
}
}
if(reptCharsCount > maxCount) {
ele = str1[i];
maxCount = reptCharsCount;
}
}
return ele;
}
Although all the answers are correct posting my way of doing it
/Question: For the given string such as "aabbbbbcc" print the longest occurring character,
index and number of times it occurs.
Ex:
"longest occurring character is b and length is 5 at index 2"./
class Codechef {
public static void main (String[] args) {
String problem = "aabbbbbcc";
Map<Character,Temp> map = new HashMap<>();
for(int i = 0; i < problem.length(); i++){
if (map.containsKey(problem.charAt(i))) {
map.get(problem.charAt(i)).incrementCount();
} else {
map.put(problem.charAt(i), new Temp(i, 1, problem.charAt(i)));
}
}
List<Map.Entry<Character, Temp>> listOfValue = new LinkedList<Map.Entry<Character, Temp>>(map.entrySet());
Comparator<Map.Entry<Character, Temp>> comp = (val1, val2) -> (val1.getValue().getCount() < val2.getValue().getCount() ? 1: -1);
Collections.sort(listOfValue, comp);
Temp tmp = listOfValue.get(0).getValue();
System.out.println("longest occurring character is "+ tmp.getStr()+ " and length is " + tmp.getCount()+ " at index "+ tmp.getIndex());
}}
And then created one Model class to keep these values
class Temp {
Integer index;
Integer count;
Character str;
public Temp(Integer index, Integer count, Character str ){
this.index = index;
this.count = count;
this.str = str;
}
public void incrementCount(){
this.count++;
}
public Integer getCount(){
return count;
}
public Character getStr(){
return str;
}
public Integer getIndex(){
return index;
}}
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;
public class Maxchar {
public static void main(String[] args) {
String str = "vaquar khan.";
// System.out.println();
System.out.println(maxChar(str));
String testcase1 = "Hello! Are you all fine? What are u doing today? Hey Guyz,Listen! I have a plan for today.";
System.out.println(maxChar(testcase1));
}
private static char maxChar(String str) {
if (null == str)
return ' ';
char[] charArray = str.replaceAll("\s+", "").toCharArray();
//
Map<Character, Integer> maxcharmap = new HashMap<Character, Integer>();
//
for (char c : charArray) {
if (maxcharmap.containsKey(c)) {
maxcharmap.put(c, maxcharmap.get(c) + 1);
} else {
maxcharmap.put(c, 1);
}
// Inside map we have word count
// System.out.println(maxcharmap.toString());
}
//
//
Set<Entry<Character, Integer>> entrySet = maxcharmap.entrySet();
int count = 0;
char maxChar = 0;
//
for (Entry<Character, Integer> entry : entrySet) {
if (entry.getValue() > count) {
count = entry.getValue();
maxChar = entry.getKey();
}
}
System.out.println("Maximum Occurring char and its count :");
System.out.println(maxChar + " : " + count);
return maxChar;
}
}
If you're open to 3rd party libraries you could use the Bag type from Eclipse Collections and select the top occurrences.
public char[] maxOccurringChar(String s) {
MutableCharBag bag = CharBags.mutable.of(s.toCharArray());
MutableList<CharIntPair> maxOccurringCharsWithCounts = bag.topOccurrences(1);
MutableCharList maxOccurringChars = maxOccurringCharsWithCounts.collectChar(CharIntPair::getOne);
return maxOccurringChars.toArray();
}
Note in this example we used the primitive collections to avoid boxing of the char and int types.
import java.util.*;
import java.util.stream.*;
class MaxOccur{
public static void main(String[] args){
String str = "sfowfjalkfaeffawkefjweajjwjegjoweeowe";
maxOcc(str);
}
public static void maxOcc(String s){
ArrayList<Character> arr = (ArrayList<Character>) s.chars().mapToObj(e ->(char)e).collect(Collectors.toList());
HashSet<Character> hs = new HashSet<>(arr);
int max = 0;
int f = 0;
String answer = "";
for(Character ch : hs){
f = Collections.frequency(arr,ch);
if(f>max){
max = f;
answer = ch;
}
System.out.println(ch + " occurs " + max + " times, the maximum");
}
}
In above, I'm using streams. Following are the steps:
Converting string's characters to arraylist using streams.
Making a hashset (discards all duplicate occurences of characters) using the arrayList created in step 1.
Use Collections.frequency to count occurence of each character in arrayList.
It's not the easiest solution, neither is it really adorable! But, it makes use of streams, something which i recently started learning and wanted to apply. I'm no adept in using streams, but they are beautiful. I've learnt most of them here on stackoverflow, and i'm so grateful. :)
Map the chars to their occurrence then query entries for the max value and get its key, note this will return the first char that has the highest occurrence
"abc".chars().mapToObj(c -> (char) c)
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
.entrySet()
.stream()
.max(Comparator.comparingLong(Map.Entry::getValue))
.get()
.getKey();
Here I am posting the answer by using HashMap
public class maximumOccurrence {
public static Map<Character,Integer> maximumOccurence(String s) {
char maxchar='';
int maxint=0;
Map<Character,Integer> map = new HashMap<Character, Integer>();
char strAtt[]= s.toCharArray();
for(Character ch : strAtt) {
if(map.containsKey(ch)) {
map.put(ch, map.get(ch)+1);
}else {
map.put(ch,1);
}
}
for(Map.Entry<Character,Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
if(maxint<entry.getValue()) {
maxint=entry.getValue();
maxchar=entry.getKey();
}
}
System.out.println("Character repeated ="+maxchar+" it's value is:"+maxint);
return map;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String s= "uuuiiiiiiiiiiioooooopp";
System.out.println(maximumOccurence(s));
}
}

Categories

Resources