Count occurence of a character in a string - java

I tried to count the occurrence of alphabets in a string, but I substitue them with numbers to make it clearer. Then when I run that code, it doesnt display the results I want.I dont really know why...Please help!! Thank you so much!!
Scanner Scanner1 = new Scanner(System.in);
out.println("Please type in a string below.");
String UserInput = Scanner1.nextLine();
String Index = "12345";
int length = 2;//Modified
int[] count = new int[length];
int length2 = 5; //Modified
int n1 = 0;
int n2 = 0;
out.println(UserInput.charAt(n1));//Modified
out.println(Index.charAt(n2));//Modified
for (int i = 0; i < length; i++) {
if (UserInput.charAt(n1) == Index.charAt(n2)) {
n1++;
count[length - (length - n1)]++;
} else {
n2++;
if(n2==length2)
{
n2 = n2-length2;
}
}
}

A relatively short and neat way to count a specific character in a string is using the return value of the replaceAll method:
public static int countChar(final String str, final char c) {
return str.replaceAll("[^" + c + "]","").length();
}
The pattern [^x] (x can be replaced with any char (or amount of different chars)) will match everything in a given String except x. So [^T] of TEST would replace E and S with the given replacement (which is "" (nothing)) and keeps the Ts. The method would return TT. If you count that length, you'll receive the count of the searched character of the given string.
The example
System.out.println(countChar("TEST", 'T'));
System.out.println(countChar("TEST", 'E'));
System.out.println(countChar("TEST", 'S'));
prints
2
1
1
(keep in mind that is method is case sensitive)

use collections like Hashmap. Here Character stores every unique character encountered and Integer stores the count of every character whenever it is encountered.

Related

searching a Char letter by letter

Trying to search for patterns of letters in a file, the pattern is entered by a user and comes out as a String, so far I've got it to find the first letter by unsure how to make it test to see if the next letter also matches the pattern.
This is the loop I currently have. any help would be appreciated
public void exactSearch(){
if (pattern==null){UI.println("No pattern");return;}
UI.println("===================\nExact searching for "+patternString);
int j = 0 ;
for(int i=0; i<data.size(); i++){
if(patternString.charAt(i) == data.get(i) )
j++;
UI.println( "found at " + j) ;
}
}
You need to iterate over the first string until you find the first character of the other string. From there, you can create an inner loop and iterate on both simultaneously, like you did.
Hint: be sure to look watch for boundaries as the strings might not be of the same size.
You can try this :-
String a1 = "foo-bar-baz-bar-";
String pattern = "bar";
int foundIndex = 0;
while(foundIndex != -1) {
foundIndex = a1.indexOf(pattern,foundIndex);
if(foundIndex != -1)
{
System.out.println(foundIndex);
foundIndex += 1;
}
}
indexOf - first parameter is the pattern string,
second parameter is starting index from where we have to search.
If pattern is found, it will return the starting index from where the pattern matched.
If pattern is not found, indexOf will return -1.
String data = "foo-bar-baz-bar-";
String pattern = "bar";
int foundIndex = data.indexOf(pattern);
while (foundIndex > -1) {
System.out.println("Match found at: " + foundIndex);
foundIndex = data.indexOf(pattern, foundIndex + pattern.length());
}
Based on your request, you can use this algorithm to search for your positions:
1) We check if we reach at the end of the string, to avoid the invalidIndex error, we verify if the remaining substring's size is smaller than the pattern's length.
2) We calculate the substring at each iteration and we verify the string with the pattern.
List<Integer> positionList = new LinkedList<>();
String inputString = "AAACABCCCABC";
String pattern = "ABC";
for (int i = 0 ; i < inputString.length(); i++) {
if (inputString.length() - i < pattern.length()){
break;
}
String currentSubString = inputString.substring(i, i + pattern.length());
if (currentSubString.equals(pattern)){
positionList.add(i);
}
}
for (Integer pos : positionList) {
System.out.println(pos); // Positions : 4 and 9
}
EDIT :
Maybe it can be optimized, not to use a Collection for this simple task, but I used a LinkedList to write a quicker approach.

breaking down any String

Hi guys I am busy with breaking / splitting Strings.
However the String is not fixed so when the input changes the program still has to work with any character input.
Till now I got this far but I got lost.
I have made an array of characters and set the size of the array equal to the lenght of any string that is will get as input. I made a for loop to loop through the characters of a string.
how do I insert my string now into the array because I know that my string is not yet in there? Then when its finally looping through the characters of my string is has to printout numbers and operands on different lines. So the ouput would look like in this case like this;
1
+
3
,
432
.
123
etc
I want to do this without using matchers,scanner, etc. I want to use basic Java techniques like you learn in the first 3 chapters of HeadfirstJava.
public class CharAtExample {
public static void main(String[] args) {
// This is the string we are going to break down
String inputString = "1+3,432.123*4535-24.4";
int stringLength = inputString.length();
char[] destArray = new char[stringLength];{
for (int i=0; i<stringLength; i++);
}
You could use Character.isDigit(char) to distinguish numeric and not numeric chars as actually this is the single criteria to group multiple chars in a same line.
It would give :
public static void main(String[] args) {
String inputString = "1+3,432.123*4535-24.4";
String currentSequence = "";
for (int i = 0; i < inputString.length(); i++) {
char currentChar = inputString.charAt(i);
if (Character.isDigit(currentChar)) {
currentSequence += currentChar;
continue;
}
System.out.println(currentSequence);
System.out.println(currentChar);
currentSequence = "";
}
// print the current sequence that is a number if not printed yet
if (!currentSequence.equals("")) {
System.out.println(currentSequence);
}
}
Character.isDigit() relies on unicode category.
You could code it yourself such as :
if (Character.getType(currentChar) == Character.DECIMAL_DIGIT_NUMBER) {...}
Or you could code it still at a lower level by checking that the int value of the char is included in the range of ASCII decimal values for numbers:
if(currentChar >= 48 && currentChar <= 57 ) {
It outputs what you want :
1
+
3
,
432
.
123
*
4535
-
24
.
4
It's easier than you might think.
First: to get an array with the chars of your string you just use the toCharArray() method that all strings have. ex. myString.toCharArray()
Second: When you see that a character is not a number, you want to move to the next line, print the character and then move to the next line again. The following code does exactly that :
public class JavaApplication255 {
public static void main(String[] args) {
String inputString = "1+3,432.123*4535-24.4";
char[] destArray = inputString.toCharArray();
for (int i = 0 ; i < destArray.length ; i++){
char c = destArray[i];
if (isBreakCharacter(c)){
System.out.println("\n" + c);
} else {
System.out.print(c);
}
}
}
public static boolean isBreakCharacter(char c){
return c == '+' || c == '*' || c == '-' || c == '.' || c == ',' ;
}
char[] charArray = inputString.toCharArray();
Here is a possible solution where we go character by character and either add to an existing string which will be our numbers or it adds the string to the array, clears the current number and then adds the special characters. Finally we loop through the array as many times as we find a number or non-number character. I used the ASCII table to identify a character as a digit, the table will come in handy throughout your programming career. Lastly I changed the array to a String array because a character can't hold a number like "432", only '4' or '3' or '2'.
String inputString = "1+3,432.123*4535-24.4";
int stringLength = inputString.length();
String[] destArray = new String[stringLength];
int destArrayCount = 0;
String currentString = "";
for (int i=0; i<stringLength; i++)
{
//check it's ascii value if its between 0 (48) and 9 (57)
if(inputString.charAt(i) >= 48 && inputString.charAt(i) <= 57 )
{
currentString += inputString.charAt(i);
}
else
{
destArray[destArrayCount++] = currentString;
currentString = "";
//we know we don't have a number at i so its a non-number character, add it
destArray[destArrayCount++] = "" + inputString.charAt(i);
}
}
//add the last remaining number
destArray[destArrayCount++] = currentString;
for(int i = 0; i < destArrayCount; i++)
{
System.out.println("(" + i + "): " + destArray[i]);
}
IMPORTANT - This algorithm will fail if a certain type of String is used. Can you find a String where this algorithm fails? What can you do to to ensure the count is always correct and not sometimes 1 greater than the actual count?

How to find the index of first occurence of any character from another string in a string?

/* returns the index of the first occurrence of any of the
* characters in chars in String s or -1 if none of the characters
* in chars are found in s. */
Above are the instructions, below is my code.
public static void main(String[] args){
indexOfAny("kabomba","bomb");
}
public static int indexOfAny(String s, String chars) {
int index = 0;
String rev = "";
for(int i = s.length()-1;i>=0;i--){
rev+=s.charAt(i);
}
String x = rev;
for(int i = 0;i<x.length();i++){
for(int j = 0; j<chars.length();j++){
if(x.charAt(i)==chars.charAt(j)){
index = i;//**
}else {
index = -1;
}
}
}
System.out.println(index);
return index;
}
To rephrase, the problem is at ** where the it will reach string x last character and compare if the characters in chars string are same and return -1, but I want the code to end and return the index of string x at the i after the last occurrence of any of characters from string chars in string x.
so the output should be 4. because the index of b, which is one of characters of string chars, in the reverse string is 4, which is what I want.
You can use StringUtils class which prevents to iterate the loop.
Here are the indexOf methods present.
OR
You can use String.indexOf method which is present under string class.
IndexOf is already available as part of std java.

Can't find logic errors

The code should do the following:
Write a method called compress that takes a string as input, compresses it using RLE, and returns the compressed string. Case matters - uppercase and lowercase characters should be considered distinct. You may assume that there are no digit characters in the input string. There are no other restrictions on the input - it may contain spaces or punctuation. There is no need to treat non-letter characters any differently from letters.If a character does not repeat, it should be left alone.
For example, consider the following string:
qwwwwwwwwweeeeerrtyyyyyqqqqwEErTTT
After applying the RLE algorithm, this string is converted into:
q9w5e2rt5y4qw2Er3T
However, when I upload it the grading system gives a zero and gives me the following hints:
Double check your algorithm for logical errors (2 occurrences)
Double check that you are compressing single characters properly (2 occurrences)
I am not sure where the errors are since all the test cases I used the output was correct.
Here is my compress method:
public static String compress (String original)
{
StringBuilder compressed = new StringBuilder();
char letter = 0;
int count = 1;
for (int i = 0; i < original.length(); i++) {
if (letter == original.charAt(i)) {
count = count + 1;
}
else {
compressed = count !=1 ? compressed.append(count) : compressed;
compressed.append(letter);
letter = original.charAt(i);
count = 1;
}
}
compressed = count !=1 ? compressed.append(count) : compressed;
compressed.append(letter);
return compressed.toString();
}
Base on the definition of RLE https://en.wikipedia.org/wiki/Run-length_encoding
Single character should have also have a count in front of them.
So the result should be
1q9w5e2r1t5y4q1w2E1r3T
Instead of
q9w5e2rt5y4qw2Er3T
Therefore, you need to change
compressed = count !=1 ? compressed.append(count) : compressed;
To just
compressed.append(count);
Below is one way to resolve it, I treat the previousLetter a bit differently from you:
public static String compress(String original) {
if (original.isEmpty()) return "";
StringBuilder compressed = new StringBuilder();
char previousLetter = original.charAt(0); // initialize the previous letter
int count = 1;
// start searching from the second letter
for (int i = 1; i < original.length(); i++) {
if (previousLetter == original.charAt(i)) {
count = count + 1;
} else {
compressed.append(count);
compressed.append(previousLetter);
previousLetter = original.charAt(i);
count = 1;
}
}
compressed.append(count);
compressed.append(previousLetter);
return compressed.toString();
}

How to count if a specific string matches while iterating through a loop in java?

This is for a past homework assignment that I wasn't able to complete in time. I am a new programmer struggling with this method of the program CharacterSearch. I'm stuck on which boolean logic to use for my if statement, as well as how to find matches in the phrase using the pre-defined character variable. And example test is: character = "x" , phrase = "Xerox". Whereas X and x are different. The expected output should be count = 1.
Edit: This problem should be answered without using arrays or lists.
/**
* Counts and returns the number of times the letter for this class
* occurs in the phrase. The class is case sensitive.
*/
public int letterCount(String phrase)
{
Scanner jf = new Scanner(phrase);
count = 0;
for (int i = phrase.length(); i > 0; i--)
{
jf.findInLine(character);
if(jf.hasNext())
{
count++;
jf.next();
}
}
return count;
}
There you go:
/**
* Counts and returns the number of times the letter for this class
* occurs in the phrase. The class is case sensitive.
*/
public int letterCount(String phrase)
{
int count = 0;
// for every character in phrase ...
for (int i = 0; i < phrase.length(); i++)
{
// ... if it is the right one ...
if(phrase.charAt(i) == character)
{
// ... increment the counter
count++;
}
}
return count;
}
You don't need any Scanner, and the code is fairly easy, readable and comprehensible.
Pretty much a duplicate of Simple way to count character occurrences in a string
I can't leave a comment yet because my rep is too low but I wanted to give you a solution you could use.
public int letterCount(String phrase)
{
count = 0;
for (int i = 0 ; i < phrase.length(); i++)
{
String myLetter = phrase.substring(i, i + 1);
if (myLetter.equals(character))
{
count++;
}
}
return count;
}
I figured out that I was iterating in the wrong direction, but more importantly I was not declaring a sub-string to check if my character matched the individual letters within the phrase.
Use String's substring with a compare().
public int letterCount(String phrase, String match)
{
int count = 0;
for(int i=0;i<phrase.length()-1;i++){ //-1 avoid out-of-bound exception
String letter = phrase.substring(i, i+1);
if(letter.compareTo(match) == 0){
count++;
}
}
return count;
}

Categories