227k views
5 votes
Characters of a String

Write a static method charCount() that

Takes a string and a file name as a arguments and throws an IOException
The method prints out a table into the file
for each character that occurs in the string the table contains
the character
and its frequency of occurrence.
Assume that the string contains only ASCII characters.
Any IOExceptions that arise are not caught but being propagated into the calling code.


Sample string: Alex A.

Output:

1
. 1
A 2
e 1
l 1
x 1


Suggested approach

Create an array of short integers
where each element is holding
The frequency of occurrence of a character with specific character code.
The element of the array is associated with the character ASCII code via element index
for example
element with index 65 is holding the frequency of character A.
Use the array as storage for the frequencies of the characters, incrementing the corresponding frequency each time you encounter the character in the given string.
Requirement: The method must be efficient – it must complete the task with only ONE pass through the string.

User Spats
by
7.9k points

1 Answer

1 vote

Answer:

Here is a sample implementation of the `charCount()` method:

```java

import java.io.*;

public class CharCount {

public static void charCount(String str, String fileName) throws IOException {

int[] charFrequency = new int[128]; // Assuming ASCII characters

// Count the frequency of each character in the string

for (char c : str.toCharArray()) {

charFrequency[c]++;

}

// Print the table into the file

try (PrintWriter writer = new PrintWriter(new FileWriter(fileName))) {

for (int i = 0; i < charFrequency.length; i++) {

if (charFrequency[i] > 0) {

writer.println((char) i + " " + charFrequency[i]);

}

}

}

}

public static void main(String[] args) {

try {

charCount("Alex A.", "output.txt");

} catch (IOException e) {

// Handle IOException

e.printStackTrace();

}

}

}

```

((This implementation uses an array `charFrequency` of size 128 to store the frequency of occurrence for each ASCII character. It iterates through the characters of the given string and increments the corresponding frequency in the array. Finally, it writes the table with characters and their frequencies into the specified file using a `PrintWriter`.

Note that any `IOExceptions` that arise during file operations are not caught in the `charCount()` method but propagated to the calling code, where they should be handled appropriately.))

User Jfn
by
7.9k points