Counting the number of occurences of characters in a string [duplicate] - java

This question already has answers here:
Java compressing Strings
(21 answers)
Closed 8 years ago.
I am trying to write a Java program which takes in as input a string and counts the number of occurrences of characters in a string and then prints a new string having the character followed by the no of occurrences.
E.G.
Input String:
aaaabb
Output String:
a4b2
Input String:
aaaaabbbc
Output String:
a5b3c1
I am posting my java code.
It is throwing StringOutOfBoundException
/*Write a routine that takes as input a string such as "aabbccdef" and o/p "a2b2c2def" or "a4bd2g4" for "aaaabddgggg".*/
import java.util.Scanner;
public class CountingOccurences {
public static void main(String[] args) {
Scanner inp= new Scanner(System.in);
String str;
char ch;
int count=0;
System.out.println("Enter the string:");
str=inp.nextLine();
while(str.length()>0)
{
ch=str.charAt(0);
int i=0;
while(str.charAt(i)==ch)
{
count =count+i;
i++;
}
str.substring(count);
System.out.println(ch);
System.out.println(count);
}
}
}

This is the problem:
while(str.charAt(i)==ch)
That will keep going until it falls off the end... when i is the same as the length of the string, it will be asking for a character beyond the end of the string. You probably want:
while (i < str.length() && str.charAt(i) == ch)
You also need to set count to 0 at the start of each iteration of the bigger loop - the count resets, after all - and change
count = count + i;
to either:
count++;
... or get rid of count or i. They're always going to have the same value, after all. Personally I'd just use one variable, declared and initialized inside the loop. That's a general style point, in fact - it's cleaner to declare local variables when they're needed, rather than declaring them all at the top of the method.
However, then your program will loop forever, as this doesn't do anything useful:
str.substring(count);
Strings are immutable in Java - substring returns a new string. I think you want:
str = str.substring(count);
Note that this will still output "a2b2a2" for "aabbaa". Is that okay?

public class StringTest{
public static void main(String[] args){
String s ="aaabbbbccccccdd";
String result="";
StringBuilder sb = new StringBuilder(s);
while(sb.length() != 0){
int count = 0;
char test = sb.charAt(0);
while(sb.indexOf(test+"") != -1){
sb.deleteCharAt(sb.indexOf(test+""));
count++;
}
//System.out.println(test+" is repeated "+count+" number of times");
result=result+test+count;
}
System.out.println(result);
}
}

I don't want to give out the full code. So I want to give you the challenge and have fun with it. I encourage you to make the code simpler and with only 1 loop.
Basically, my idea is to pair up the characters comparison, side by side. For example, compare char 1 with char 2, char 2 with char 3, and so on. When char N not the same with char (N+1) then reset the character count. You can do this in one loop only! While processing this, form a new string. Don't use the same string as your input. That's confusing.
Remember, making things simple counts. Life for developers is hard enough looking at complex code.
Have fun!
Tommy "I should be a Teacher" Kwee

if this is a real program and not a study project, then look at using the Apache Commons StringUtils class - particularly the countMatches method.
If it is a study project then keep at it and learn from your exploring :)

You should be able to utilize the StringUtils class and the countMatches() method.
public static int countMatches(String str,
String sub)
Counts how many times the substring appears in the larger String.
Try the following:
int count = StringUtils.countMatches("a.b.c.d", ".");

I think what you are looking for is this:
public class Ques2 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine().toLowerCase();
StringBuilder result = new StringBuilder();
char currentCharacter;
int count;
for (int i = 0; i < input.length(); i++) {
currentCharacter = input.charAt(i);
count = 1;
while (i < input.length() - 1 && input.charAt(i + 1) == currentCharacter) {
count++;
i++;
}
result.append(currentCharacter);
result.append(count);
}
System.out.println("" + result);
}
}

Try this:
import java.util.Scanner;
/* Logic: Consider first character in the string and start counting occurrence of
this character in the entire string. Now add this character to a empty
string "temp" to keep track of the already counted characters.
Next start counting from next character and start counting the character
only if it is not present in the "temp" string( which means only if it is
not counted already)
public class Counting_Occurences {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
System.out.println("Enter String");
String str=input.nextLine();
int count=0;
String temp=""; // An empty string to keep track of counted
// characters
for(int i=0;i<str.length();i++)
{
char c=str.charAt(i); // take one character (c) in string
for(int j=i;j<str.length();j++)
{
char k=str.charAt(j);
// take one character (c) and compare with each character (k) in the string
// also check that character (c) is not already counted.
// if condition passes then increment the count.
if(c==k && temp.indexOf(c)==-1)
{
count=count+1;
}
}
if(temp.indexOf(c)==-1) // if it is not already counted
{
temp=temp+c; // append the character to the temp indicating
// that you have already counted it.
System.out.println("Character " + c + " occurs " + count + " times");
}
// reset the counter for next iteration
count=0;
}
}
}

Related

How does the if block remove repeating characters?

Could some of you please explain to me how exactly does the if part works in this code --
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Input a word: ");
String word = "Programming in Java.";
String result = "";
for (int i = 0; i < word.length(); i++){
// ***** HERE *****
if (word.indexOf(word.charAt(i)) == i){
result += word.charAt(i);
}
// *****
}
System.out.println(result);
}
The code is removing all the repeating characters and I cannot put my finger as of how it exactly it does that and I want to fully understand how it works before I continue studying.
I refer you to the String.indexOf(int) Javadoc which says (in part)
Returns the index within this string of the first occurrence of the specified character.
When you say if(word.indexOf(word.charAt(i)) == i) that is the same as saying if the current char is the first occurrence of the current char append it to the result. Otherwise don't append it. Thus, it only adds characters if it is their first appearance.

Counting a specific character in a string using a recursive method in Java

My homework is to make a recursive method to count the appearances of a given letter in a given string. Here is my code so far:
import java.util.Scanner;
public class Exercise18_10 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = sc.next();
System.out.print("Enter a character: ");
String letter = sc.next();
char a = letter.charAt(0);
System.out.println("The count of " + a + " is: " + count(str, a));
}
public static int count(String str, char a) {
int count = str.indexOf(a);
return count;
}
}
In count, I use indexOf to find the first occurrence of the desired letter, but I'm not sure what to do after that.
Your count variable is the position of the first occurrence in the string. Instead, you need something like
public static int count(String str, char a) {
int exist = str.indexOf(a);
if ( <a doesn't exist in str*> )
return 0;
else { /* recur on the rest of the string; add 1 */
rest = str.substr(exist+1, <end of string>)
return count(rest, a) + 1
}
}
I've left a lot of this for you to code, but those are the two basic steps:
Base case: the character isn't there, so return 0
Recursion: count one sighting, add whatever is in the rest of the string.
As you stated, 'count' function currently returns the index of first occurrence of an inputted letter. The idea of counting the number of occurrences recursively would mean you need to break the string down into smaller and smaller parts as you move forward.
First, you look at the whole string, then only the substring of the current string beginning with the next occurrence and so on. To implement recursion here, you might want to create a method which can call itself repeatedly (like Inception!) with a base condition to break out once you're done (i.e. reaching the end of a string or finding no more occurrences of the character in whatever portion of the string you have left --> indexOf(...) == -1)

Can't figure out what is wrong with my code

This is the instructions i got from my teacher:
Write your code in the file WordCount.java. Your code should go into a method with the following signature. You may write your own main method to test your code. The graders will ignore your main method:
public static int countWords(String original, int minLength){}
Your method should count the number of words in the sentence that meet or exceed minLength (in letters). For example, if the minimum length given is 4, your program should only count words that are at least 4 letters long.
Words will be separated by one or more spaces. Non-letter characters (spaces, punctuation, digits, etc.) may be present, but should not count towards the length of words.
Hint: write a method that counts the number of letters (and ignores punctuation) in a string that holds a single word without spaces. In your countWords method, break the input string up into words and send each one to your method.
This is my code:
public class WordCount {
public static void main(String[] args)
{
System.out.print("Enter string: ");
String input = IO.readString();
System.out.print("Enter minimum length for letter: ");
int length = IO.readInt();
IO.outputIntAnswer(countWords(input, length));
}
public static int countWords(String original, int minLegth)
{
int count = 0;
int letterCount = 0;
for(int i = 0; i < original.length(); i++)
{
char temp = original.charAt(i);
if(temp >= 'A' && temp <= 'Z' || temp >= 'a' && temp <= 'z')
{
letterCount++;
}
else if(temp == ' '|| i == original.length()-1)
{
if(letterCount >= minLegth)
{
count++;
}
letterCount = 0;
}
}
return count;
}
}
My college uses an autograder to grade project and i am keep getting one of the test case wrong. Can someone help me figure out what the problem is?
I figured the problem that your code is not able to compare the last character.It expects a space after the last character so that it can compare the last character since java doesn't use null character terminator for string termination.I have emulated the same code using Scanner class as I was having some trouble with io.So I have done the following change:
Scanner sc1,sc2;
sc1=new Scanner(System.in);
String input = sc1.nextLine()+" ";
I don't know if its possible to do:
String input = IO.readString()+" ";
but i think you should try appending blank space " " at the end of the string

Trying to write a simple compiler in java (I am using notepad++)

My question is how would I write a simple compiler ,that is like the compilers used in fax machines, that would convert something like aaaavvvvvddddddddddd to 4a5vBd.
Also, I get to "Assume" that any string entered will not contain uppercase letters and no numbers, and that any string will contain less than 61 of any type of character so, I get to assume no one will put in 64 continues a's in my program.
This is as far as I gotten
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n;
char cn;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Hello, please enter a string");
word = scan.nextln();
if(n <= 61)
{
int n = ?;
cn = numChars.charAt(n);
}
}
}
I assume I need to use a loop, but I don't know what I should use to count the repeating letters and then tell how many letters of that type are in a row. Now I am only asking for advice and not so much for code, because I want to do it but, as a beginner my Java "Vocabulary" isn't very big right now.
Any advice/ tips would be greatly appreciated.
Sincerely,
Mr.Trips
Well I am back and it appears my code here likes to only print out 147. No matter what I type in I will always get 147. I have tried to hand trace all my variables, but when I do it I get exactly what I want, and I must have some error in my logic. Any thoughts?
import java.util.*;
public class Program4
{
public static void main(String[] args)
{
Scanner scan = new Scanner(System.in);
int n = 0;
int s = 0;
char a;
char b;
char c;
String word;
String numChars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
System.out.println("Please enter a string");
word = scan.nextLine();
while (n < word.length())
{
a = word.charAt(n);
b = a;
n = n ++;
a = word.charAt(n);
if (a == b)
{
s = (s + 1) ;
}
else if (a != b);
{
c = numChars.charAt(s);
System.out.print(b + c);
s = 0;
c = 0;
break;
}
}
}
}
Thank you again!
Since you don't want code this is logically how to do it. You are right you should loop through the string for each char. Store the last char in a variable and keep a counter variable. Compare current char to last char if it is equal then increment the counter. As soon as it is not equal to the last char then add counter + last char to result string and reset counter variable. Each iteration update last char variable.

Java program to calculate the number of times each character appears in a string [duplicate]

This question already has answers here:
How to count frequency of characters in a string?
(27 answers)
Closed 9 years ago.
I typed out this program to count the number of times each character appears in a String.
import java.util.Scanner;
public class fre {
public static void main(String[] args) {
Scanner s=new Scanner (System.in);
System.out.println("Enter a string");
String sent = s.nextLine();
String str=sent.toUpperCase();
int len=str.length();
char save[]=new char[len];
for (int i=0;i<len;i++){
save[i]=str.charAt(i);
}
char a=0;
int count=0;
for(int i=0;i<len;i++){
a=save[i];
for(int j=0;j<len;j++){
if(save[j]==a)
count ++;
}
}
for(int i=0;i<len;i++)
System.out.println(save[i]+" appears "+count+" number of times");
}
}
The code is horribly wrong, can someone please guide me as to how to go about the program using simple functions and tell me what I've done wrong here?
You can do it simply by
Declaring an array of 26 integers (1st index refers to A, second to B and so on)
Just traverse the input string once and for each character you traverse in string, increment corresponding index, you can do it simply like int index=inputString[i]-65; and increment this index.
Now traverse your array for the counts of each character and you are done, Hope it helps
How about
int[] count = new int[256];
for(int ch; (ch = System.in.read()) >= ' ';)
count[ch]++;
for(char ch = 0; ch < count.length; ch++)
if (count[ch] > 0)
System.out.println(ch + " appears " + count[ch] + " times");
You need a separate count for each character. Right now you are incrementing the same count.
You have one global count while you need one counter for each character.
Try using a Map<Character, Integer> to store the number of occurences of each character in your string.
If i understand what you want is something like this:
int count = StringUtils.countMatches("Auto-generated method stub", "e");
System.out.println(count);
StringUtils is a api from apache http://commons.apache.org/proper/commons-lang/
You can also use Collections.frequency(Collection<?> c, Object o) method to get count of an element in a collection, So below code snippet will give you the character count in a string.
String str=s.nextLine().toUpperCase();
char[] letters=str.toCharArray();
List<Character> cList = new ArrayList<Character>();
for(char c : letters) {
cList.add(c);
}
Set<Character> chSet=new HashSet<Character>(cList); //to get unique characters in the list
for(Character ch:chSet) {
System.out.println(ch+" "+Collections.frequency(cList, ch));
}

Categories