how to count the number of letters in an array java - java

I have an assignment about how to count the number of letters in an array.
Here is my code:
import java.util.Scanner;
public class task1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Create a scanner object
Scanner input = new Scanner(System.in);
//Prompt user's input
System.out.println("Enter strings (use a space to separate them; hit enter to finish) : ");
String str = input.nextLine();
// use split to divide the string into different words cutting by " "
String [] wordsArray = str.trim().split(" ");
System.out.println("The length of string is " + wordsArray.length);
for(int i = 0 ; i < wordsArray.length; i++){
char [] eachLetterinArray = wordsArray[i].toCharArray();
for(int j = 0,count = 0 ; j < eachLetterinArray.length; j++){
if( (eachLetterinArray[j]+'a'-97 >=65 && eachLetterinArray[j]+'a'-97 <=90 )
|| (eachLetterinArray[j]+'a'-97 >=97 && eachLetterinArray[j]+'a'-97 <=122 ) ){
count++;
}
System.out.print(count);
}
}
}
if I enter "end tr"
the output is "12312"
but what I want is "3 and 2 "
I have tried a lot and still have nothing to do about this...
can you help me?

You want to print count per word, but you are printing for each character. Just print the count variable outside of the inner loop.
for (int i = 0; i < wordsArray.length; i++) {
char[] eachLetterinArray = wordsArray[i].toCharArray();
int count = 0;
for (int j = 0; j < eachLetterinArray.length; j++) {
if ((eachLetterinArray[j] + 'a' - 97 >= 65 && eachLetterinArray[j] + 'a' - 97 <= 90)
|| (eachLetterinArray[j] + 'a' - 97 >= 97 && eachLetterinArray[j] + 'a' - 97 <= 122)) {
count++;
}
}
System.out.println(count);
}
Improvement:
Instead of the little bit complex condition, you can do this way also:
if (Character.isLetter(eachLetterinArray[j])) {
count++;
}

int countedLength = 0;
for(String string: arrayList) {
countedLength += string.length();
}
//Your count of Number of Letters in Array
System.out.pritnln(countedLength);
Or if you want to count every letter unique, do a new for in this for like
if(letter.equals("a")) {
letterVariableCountA++;
}

You are using space to split the word and count the letters. So use split() on string.
split() takes a string which splits the word. In your case it is space.
It returns splitted strings as an array. Just iterate over strings and use length() on string to get the number of characters present in the word.
public class Main
{
public static void main(String[] args)
{
int count;
String s = "This is your string for example";
String[] split = s.split(" ");
for(String str: split)
{
char[] ch = str.toCharArray(); // convert string to char array
count = 0; // reset count for every new word/string
for(char c: ch) // iterate over all the characters
{
if(Character.isLetter(c)) // Returns true if the character is a Letter
{
count++; // increase the count to represent no. of letters
}
}
System.out.print(count + " "); // print the no.of characters that are letters in a word/string.
}
}
}

This should do the trick, you were printing your count within the loop which is why it was counting. If you set the inital count value outside of it, you can then print it once the loop is complete, and then set it back to 0 before it starts on the next word.
public static void main(String[] args) {
String str = "test1 phrase";
int count = 0;
// use split to divide the string into different words cutting by " "
String[] wordsArray = str.trim().split(" ");
System.out.println("The length of string is " + wordsArray.length);
for (int i = 0; i < wordsArray.length; i++) {
char[] eachLetterinArray = wordsArray[i].toCharArray();
for (int j = 0; j < eachLetterinArray.length; j++) {
if ((eachLetterinArray[j] + 'a' - 97 >= 65 && eachLetterinArray[j] + 'a' - 97 <= 90)
|| (eachLetterinArray[j] + 'a' - 97 >= 97 && eachLetterinArray[j] + 'a' - 97 <= 122)) {
count++;
}
}
System.out.print(count + "\n");
count = 0;
}
}
with the above example I got an output of
The length of string is 2
4
6

Related

Counting the Number of Identical Character to its Right in a Sentence in Java

In java, I am suppose to examine each character in the sentence, from left to right and count the number of identical characters to its right and print the count.
Scanner K = new Scanner(System.in);
String s = K.nextLine();
for (int i = 0; i < s.length(); i++) {
int count = 0;
while (i+1 < s.length() && s.charAt(i)== s.charAt(i + 1))
{
i++;
count++;
}
System.out.print(s.charAt(i)+ ":");
System.out.println(count);
}
System.out.println();
}
}
Example output should be like:(when i input "I love u")
I:0
: 1
l:0
o:0
v:0
e:0
:0
u:1

How to fix: Number of occurrences of a letter in a string

I'm trying to count the number of occurrences of letters that are in string. The code that I have written technically does what I want, but not the way I want to do it. For example, if I input "Hello World", I want my code to return "a=0 b=0 c=0 d=0 e=1 etc...." with the code I have written it returns "H=1, e=1, l=2 etc...."
Also how would I make sure that it is not case sensitive and it doesn't count spaces.
Code:
import java.util.Scanner;
public class Sequence {
private static Scanner scan = null;
public static void main(String[] args) {
scan = new Scanner(System.in);
String str = null;
System.out.print("Type text: ");
str = scan.nextLine();
int[] count = new int[255];
int length = str.length();
for (int i = 0; i < length; i++)
{
count[str.charAt(i)]++;
}
char[] ch = new char[str.length()];
for (int i = 0; i < length; i++)
{
ch[i] = str.charAt(i);
int find = 0;
for (int j = 0; j <= i; j++)
{
if (str.charAt(i) == ch[j])
find++;
}
if (find == 1)
{
System.out.print(str.charAt(i) + "=" + count[str.charAt(i)] + " ");
}
}
}
}
As I hinted in my original comment you only need an array of 26 int(s) because there are only 26 letters in the alphabet. Before I share the code, it is important to note that Java char is an integral type (and, for example, 'a' + 1 == 'b'). That property is important, because it allows you to determine the correct offset in an array (especially if you force the input to lower case). Something like,
Scanner scan = new Scanner(System.in);
System.out.print("Type text: ");
String str = scan.nextLine();
int[] count = new int[26];
for (int i = 0; i < str.length(); i++) {
char ch = Character.toLowerCase(str.charAt(i)); // not case sensitive
if (ch >= 'a' && ch <= 'z') { // don't count "spaces" (or anything non-letter)
count[ch - 'a']++; // as 'a' + 1 == 'b', so 'b' - 'a' == 1
}
}
for (int i = 0; i < count.length; i++) {
if (count[i] != 0) {
System.out.printf("%c=%d ", 'a' + i, count[i]);
}
}
System.out.println();
If you really want to see all of the letters that have counts of zero (seems pointless to me), change
if (count[i] != 0) {
System.out.printf("%c=%d ", 'a' + i, count[i]);
}
to remove the if and just
System.out.printf("%c=%d ", 'a' + i, count[i]);
Change str = scan.nextLine(); to str = scan.nextLine().toLowerCase().replaceAll("\\s+","");
.toLowerCase() is a method which makes every char in the string lowercase.
.replaceAll() is a method which replaces one char with another. In this case, it replaces whitespaces with nothing.

Sum of the Difference between the first letter and the last letter, second letter and the penultimate letter, and so on till the center of the word

If the given string is “WORLD WIDE WEB”
In each word, find the Sum of the Difference between the first letter and the last letter, second letter and the penultimate letter, and so on till the center of the word.
WORLD = [W-D]+[O-L]+[R] = [23-4]+[15-12]+[18] = [19]+[3]+[18] = [40]
WIDE = [W-E]+[I-D] = [23-5]+[9-4] = [18]+[5] = [23]
WEB = [W-B]+[E] = [23-2]+[5] = [21]+[5] = [26]
Concatenate the sums of each word to form the result
[40] [23] [26]
[402326]
class Strcode{
public static void main(String args[]){
int xd[]=new int[100];
int n[]=new int[100];
int position=0;
String input = "hello".toLowerCase(); //note the to lower case in order to treat a and A the same way
for( int i = 0; i < input.length(); ++i) {
position = input.charAt(i) - 'a' + 1;
System.out.println(position);
for( int k=0,j=position.length()-1;k<j;k++,j--){
xd[k]=Math.abs(xd[k]-xd[j]);
System.out.println(xd[k]);
}
}
}
}
By the above code i am able to get numerical value of letters, but failed to do next step of subtraction.
It is one of the basic problems for beginners. Let me crack it down for you. You need to perform following steps :
Extract each word from your given string. ( Do it on your own! )
Calculate sum for each word. ( Find below code! )
Concatenate these sums. ( Easy! )
public class sample{
public static void main(String args[]){
// Do your part of code here
String sampleWord = "hello";
int individualWordSum = countSum(sampleWord);
}
public static int countSum(String word){
String input = word.toLowerCase();
int sum = 0;
for( int i = 0; i < input.length()/2; i++) {
int s = (input.charAt(i) - 'a') - (input.charAt(input.length() - 1 - i) - 'a');
sum += Math.abs(s);
}
if(input.length()%2!=0){
sum += input.charAt(input.length()/2) - 'a' + 1;
}
System.out.println("sum for " + input + " is " + sum);
return sum;
}
}
Here is the complete code you need, but first try on your own.
public class sample{
public static void main(String args[]){
String sentence = "WORLD WIDE WEB";
String words[] = sentence.split(" ");
String result = "";
for(String word : words){
result += String.valueOf(countSum(word));
}
System.out.println("Sum for " + sentence + " is " + result);
}
public static int countSum(String word){
String input = word.toLowerCase();
int sum = 0;
for( int i = 0; i < input.length()/2; i++) {
int s = (input.charAt(i) - 'a') - (input.charAt(input.length() - 1 - i) - 'a');
sum += Math.abs(s);
}
if(input.length()%2!=0){
sum += input.charAt(input.length()/2) - 'a' + 1;
}
return sum;
}
}
You can make it quite simpler if instead of implementing the described logic, you analyze it and get a simpler solution.
Instead of summing up the difference between the first letter and the last letter and so on, you can sum the first half of the word (including the middle letter if the word is of odd length) and subtract the second half.
String sentance = "WORLD";
int middle = Math.ceil(sentance.length() / 2);
int sum = 0;
for (int i = 0; i < sentance.length(); i++)
{
if (i <= middle)
{
sum += sentance[i] - 'A' + 1;
}
else
{
sum -= sentance[i] - 'A' + 1;
}
}
System.out.println("Sum: " + sum);
You'll get:
Sum: 40

How to use ASCII in array

I want to write a program that takes a string text, counts the appearances of every letter in English and stores them inside an array.and print the result like this:
java test abaacc
a:***
b:*
c:**
* - As many time the letter appears.
public static void main (String[] args) {
String input = args[0];
char [] letters = input.toCharArray();
System.out.println((char)97);
String a = "a:";
for (int i=0; i<letters.length; i++) {
int temp = letters[i];
i = i+97;
if (temp == (char)i) {
temp = temp + "*";
}
i = i - 97;
}
System.out.println(temp);
}
Writing (char)97 makes the code less readable. Use 'a'.
As 3kings said in a comment, you need an array of 26 counters, one for each letter of the English alphabet.
Your code should also handle both uppercase and lowercase letters.
private static void printLetterCounts(String text) {
int[] letterCount = new int[26];
for (char c : text.toCharArray())
if (c >= 'a' && c <= 'z')
letterCount[c - 'a']++;
else if (c >= 'A' && c <= 'Z')
letterCount[c - 'A']++;
for (int i = 0; i < 26; i++)
if (letterCount[i] > 0) {
char[] stars = new char[letterCount[i]];
Arrays.fill(stars, '*');
System.out.println((char)('a' + i) + ":" + new String(stars));
}
}
Test
printLetterCounts("abaacc");
System.out.println();
printLetterCounts("This is a test of the letter counting logic");
Output
a:***
b:*
c:**
a:*
c:**
e:****
f:*
g:**
h:**
i:****
l:**
n:**
o:***
r:*
s:***
t:*******
u:*

How to find sub string of a binary string in java

String s="101010101010";
String sub=""; //substring
int k=2;
package coreJava;
import java.util.Scanner;
public class substring {
public static void main(String args[])
{
String string, sub;
int k, c, i;
Scanner in = new Scanner(System.in);
System.out.println("Enter a string to print it's all substrings");
string = in.nextLine();
i = string.length();
System.out.println("Substrings of \""+string+"\" are :-");
for( c = 0 ; c < i ; c++ )
{
for( k = 1 ; k <= i - c ; k++ )
{
sub = string.substring(c, c+k);
System.out.println(sub);
}
}
}
}
take a binary string s="1010011010"; //etc
take one variable k=2;
take another variable i; //which is the length of the sub string(i>k)
now i want to find sub string of the above string, in such a way that if k=2,the number of 1's in sub string must be 2,if k=3,the number of 1's in substring must be 3 and so on...
Output should be like this:
string s="1010011010"
Enter value of k=2;
Enter length of substring i=3;
substring= 101 110 101 011
Create a "window" the length of your desired substrings which you move along the string, maintaining a count of the number of 1s in your current window. Each iteration you move the window along one, testing the next character outside the current window, the first character in the current window and updating the count accordingly. During each iteration, if your count is equal to the desired length, print the substring from the current window.
public class Substring {
public static void main(String[] args) {
String str = "1010011010";
int k = 2;
int i = 3;
printAllSubstrings(str, i, k);
}
private static void printAllSubstrings(String str, int substringLength, int numberOfOnes) {
// start index of the current window
int startIndex = 0;
// count of 1s in current window
int count = 0;
// count 1s in the first i characters
for (int a = 0; a < substringLength; a++) {
if (str.charAt(a) == '1') {
count++;
}
}
while (startIndex < str.length() - substringLength + 1) {
if (count == numberOfOnes) {
System.out.print(str.substring(startIndex, startIndex + substringLength));
System.out.print(" ");
}
// Test next bit, which will be inside the window next iteration
if (str.length() > startIndex + substringLength && str.charAt(startIndex + substringLength) == '1') {
count ++;
}
// Test the starting bit, which will be outside the window next iteration
if (str.charAt(startIndex) == '1') {
count --;
}
startIndex++;
}
}
}
This outputs:
101 011 110 101
Iterate over the characters and count the number of one's. If the counter reaches the desired number, stop iterating and take the substring from index zero to where you got.
String str = "010101001010";
int count = 0;
int k = 2;
int i = 0;
for (; i < str.length() && count < k; ++i)
{
if (str.charAt(i) == '1') count++;
}
You could use regular expressions:
public class BinaryString {
public static void main(String[] args) {
String binary = "11000001101110";
int count = 3;
String regEx = "1{" + count + "}";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(binary);
if (m.find()) {
int startIndex = m.start();
System.out.println("MATCH (#index " + startIndex + "): "+ m.group());
} else {
System.out.println("NO MATCH!");
}
}
}
OUTPUT
MATCH (#index 10): 111

Categories