At a user entered string, I am having a tough time with the counter. The code locates the most occurring character but where can I put counter that it counts the most occurring character. In Java, with the current code please. It's the last method.
import java.util.*;
public class newTest {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter a one line sentence:");
String words = scnr.nextLine();
findAlphabetMode(words);
}
public static void findAlphabetMode(String input){
int[] freq = new int[input.length()];
char mode = input.charAt(0);
boolean noMode = true;
int counter = 0;
int steadyCount = 0;
char string[] = input.toCharArray();
for (int i = 0; i < string.length; i++){
freq[i] = 1;
for(int j = i + 1; j < string.length; j++){
if(string[i] == string[j] && string[i] != ' ' && string[i] != 0){
freq[i]++;
//counter++;
}
if(counter > 1){
if(counter > steadyCount){
steadyCount = counter + 1;
counter = 0;
}
}
if(string[i] == string[j]){
noMode = false;
string[j] = 0;
counter++;
}
}
}
int max = freq[0];
for(int i = 0; i < freq.length; i++){
if(max < freq[i]){
max = freq[i];
mode = string[i];
noMode = false;
}
}
if (noMode) {
System.out.println("Mode: No Mode");
}
else {
System.out.println("The letter " + mode + " occurs " + steadyCount + " times");
}
}
}
`
Must not be that complicated, even without streams:
public static void findAlphabetMode(String input) {
var freq = new int['z'-'a'+1];
for (var ch : input.toLowerCase().toCharArray()) {
if (ch >= 'a' && ch <= 'z') {
freq[ch-'a'] += 1;
}
}
var max = 0; // index to maximum freq
for (var i = 1; i < freq.length; i++) {
if (freq[i] > freq[max]) {
max = i;
}
}
var ch = (char) ('a' + max);
System.out.printf("found %d times %c%n", freq[max], ch);
}
Not to hard to combine second loop into first loop:
public static void findAlphabetMode(String input) {
var freq = new int['z'-'a'+1];
var max = 0; // index to maximum freq
for (var ch : input.toLowerCase().toCharArray()) {
if (ch >= 'a' && ch <= 'z') {
if (++ freq[ch-'a'] > max) {
max = ch - 'a';
}
}
}
var ch = (char) ('a' + max);
System.out.printf("found %d times %c%n", freq[max], ch);
}
Note: this only counts letters a-z after converting to lower case.
You don't need a nested for loop. That makes your algorithm O(N^2) i.e. when your input string length doubles, the time taken increases fourfold.
You can put each letter in the input string into a Map<Character, Integer>, increasing the value each time you add an existing character, and then at the end find the key with the largest value. A succinct way of doing this is to use streams:
public static void findAlphabetMode(String input) {
input.chars()
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet()
.stream()
.max(Map.Entry.comparingByValue())
.ifPresentOrElse(
e -> System.out.printf("The letter %c occurs %d times%n", e.getKey(), e.getValue()),
() -> System.out.println("No mode"));
}
If you still prefer loops you can do it like so.
iterate across the string, checking only letters
use map.merge to compute the frequency.
String s =
"To be or not to be, that is the question.";
Map<Character, Integer> map = new HashMap<>();
for (Character c : s.toCharArray()) {
if (Character.isLetter(c)) {
map.merge(c, 1, Integer::sum);
}
}
Now that the frequency is counted, just find the largest
first, make certain characters exist
otherwise, iterate across the entry set finding the maximum value and saving the associated character.
if (map.isEmpty()) {
System.out.println("Mode: No Mode");
} else {
Entry<Character, Integer> result = null;
char chr = ' ';
int count = 0;
for (Entry<Character, Integer> e : map.entrySet()) {
int val = e.getValue();
if (val > count) {
count = val;
chr = e.getKey();
}
}
System.out.printf("The letter `%c` occurs %d times.%n", chr, count );
}
prints
The letter `t` occurs 6 times.
If you want to ignore case, you can do the following in the first loop.
for (Character c : s.toLowerCase().toCharArray()) {
...
}
You don't need to separately increment counter, since you are already calculating frequency for each character, in an array, you can simply loop, over the array and find your maximum occuring character. Here is a simplified version of your code:
import java.util.*;
public class newTest {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
System.out.println("Please enter a one line sentence:");
String words = scnr.nextLine();
findAlphabetMode(words);
}
public static void findAlphabetMode(String input){
int[] freq = new int[input.length()];
char mode = input.charAt(0);
char string[] = input.toCharArray();
for (int i = 0; i < string.length; i++){
freq[i] = 1;
for(int j = i + 1; j < string.length; j++){
if(string[i] == string[j]){
freq[i]++;
}
}
}
int max = freq[0];
for(int i = 0; i < freq.length; i++){
if(max < freq[i]) {
max = freq[i];
mode = string[i];
}
}
System.out.println("The letter " + mode + " occurs " + max + " times");
}
}
Related
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.
Sort a string with small capital and numbers in Java
aAbcB1C23 .
Answer ABCabc123.
I tried sorting the array both ascending as well as decending but did not work as in both the ways ABC is coming in the middle. Any ideas ?
I'd like to solve with O(1) auxillary space and may be O(n log n) time ..
public class SortTheGivenStringAlphabetically {
public static void performAction() {
String input = "aAbcB1C23";
char[] inputCharArray = input.toCharArray();
sort(inputCharArray, 0, (inputCharArray.length) - 1);
for (int i = 0; i < inputCharArray.length; i++) {
System.out.println(inputCharArray[i]);
}
}
public static void sort(char[] array, int low, int high) {
if (low < high) {
int pi = partition(array, low, high);
sort(array, low, pi - 1);
sort(array, pi + 1, high);
}
}
private static int partition(char[] array, int low, int high) {
int pivot = array[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (array[j] <= pivot) {
i++;
char temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
char temp = array[i + 1];
array[i + 1] = array[high];
array[high] = temp;
return i + 1;
}
public static void main(String[] args) {
performAction();
}
}
Create 3 ArrayLists.
Separate all characters from the input and add them to the specific ArrayList.
Then sort them using Collections.sort().
Finally combine all the characters in the order you want.
String input = "aAbcB1C23";
ArrayList<Character> capital = new ArrayList(),
simple = new ArrayList(),
numbers = new ArrayList();
for (Character c : input.toCharArray()) {
if (Character.isLetter(c)) {
if (Character.isUpperCase(c)) {
capital.add(c);
} else {
simple.add(c);
}
} else {
numbers.add(c);
}
}
Collections.sort(simple);
Collections.sort(capital);
Collections.sort(numbers);
StringBuilder output = new StringBuilder();
for (Character c : capital) {
output.append(c);
}
for (Character c : simple) {
output.append(c);
}
for (Character c : numbers) {
output.append(c);
}
System.out.println(output.toString());
Output:
ABCabc123
The meanness is that the natural order is '1' (49) < 'A' (65) < 'a' (97).
String input = "aAbcB1C23"; // Sorted: ABCabc123
char[] array = input.toCharArray();
sort(array, 0, (array.length) - 1);
So either you could reorder the wrongly sorted result:
output = output.replaceFirst("^([0-9]*)([A-z]*)$", "$2$1");
or map every concerned char to a correct value: easiest with a function:
int value(char ch) {
if ('A' <= ch && ch <= 'Z') {
return 100 + (ch - 'A');
} else if ('a' <= ch && ch <= 'z') {
return 200 + (ch - 'a');
} else if ('0' <= ch && ch <= '9') {
return 300 + (ch - '0');
} else {
return 400 + (int) ch;
}
}
Now compare value(array[i]).
First loop iterate no of times the no of character present in String.And last two loops run for constant time (78 times).So time complexity wise it could be effecient.
public static String SortSstring(String input) {
int []intArr=new int[78];
for(int i=0;i<input.length();i++)
intArr[input.charAt(i)-48] ++;
String OutputString="";
for(int i=17;i<78;i++){
OutputString+=String.valueOf(new char[intArr[i]]).replace('\0', (char)(i+48));
}
for(int i=0;i<10;i++){
OutputString+=String.valueOf(new char[intArr[i]]).replace('\0', (char)(i+48));
}
return OutputString;
}
}
One option is to use integer value of a character when doing comparison. To make numbers appear at the end we can add some fixed value to it (e.g. 100).
public static void main(String[] args) {
String input = "aAbcB1C23";
char[] charArray = input.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(charArray);
Arrays.sort(charObjectArray, new Comparator<Character>() {
#Override
public int compare(Character o1, Character o2) {
Integer i1 = convert(Integer.valueOf(o1));
Integer i2 = convert(Integer.valueOf(o2));
return i1.compareTo(i2);
}
private Integer convert(Integer original) {
if (original < 58) {
return original + 100;
}
return original;
}
});
System.out.println(new String(ArrayUtils.toPrimitive(charObjectArray)));
}
This code supposed to output the longest run on which a character in a string has a consecutive runs of itself. Though the problem is that it outputs: 8 (which should be 5 instead). I just would like to ask what seems to be the problem regarding this code.
public class Sample {
public static void main(String[] args) {
String setofletters = "aaakkcccccczz"; /* 15 */
int output = runLongestIndex(setofletters);
System.out.println("Longest run that first appeared in index:" + output);
}
public static int runLongestIndex(String setofletters) {
int ctr = 0;
int ctrstor = 0;
int ii = 0;
int output = 0;
// loops until the last character in the string
for (int i = 0; i < setofletters.length() - 1; i++) {
// checks if the letter is the same to the next
if (setofletters.charAt(i) == setofletters.charAt(i++)) {
ctr++;
ii = i++;
// loops until the letter in the index is no longer equal
while (setofletters.charAt(i) == setofletters.charAt(ii)) {
ii++;
ctr++;
}
if (ctr > ctrstor) {
output = i;
}
// storing purposes
ctrstor = ctr;
}
// resets the counter
ctr = 0;
}
return output;
}
}
UPDATE Sorry, I misunderstood your question a bit, you need to make the following changes in your code to make it work.(lines with comments)
public static int runLongestIndex(String setofletters){
int ctr = 1; // every character is repeated at least once, so you should initialize it to 1, not 0
int ctrstor = 0;
int ii = 0;
int output = 0;
for (int i = 0; i < setofletters.length() - 1; i++) {
if (i < setofletters.length() - 1 && setofletters.charAt(i) == setofletters.charAt(i+1)) { // i++ is not same as i+1
ctr++;
ii = i+1; // i++ is not same as i+1
while (setofletters.charAt(i) == setofletters.charAt(ii)) {
ii++;
ctr++;
}
if (ctr > ctrstor) {
output = i;
}
ctrstor = ctr;
}
ctr = 1; // for the same reason I mentioned above
}
return output;
}
EDIT : the easiest way to write your code is :
public static int runLongestIndex(String setofletters){
int ctr = 1;
int output = 0;
int j=0;
for(int i=0; i<setofletters.length()-1;i++){
j=i;
while(i <setofletters.length()-1 && setofletters.charAt(i)==setofletters.charAt(i+1)){
i++;
ctr++;
}
if(ctr>output){
output=j;
}
ctr = 1;
}
return output;
}
Why are you assigning i to output? You should assign ctr to output.
change
if(ctr>ctrstor){
output=i;
}
to
if(ctr>ctrstor){
output=ctr;
}
and also I think you should change
if(setofletters.charAt(i)==setofletters.charAt(i++))
to
if(i<setofletters.length()-1 && setofletters.charAt(i)==setofletters.charAt(i+1)){
and you should intialize ctr to 1 but not 0 because every character is repeated at least once.
I'll give you a Scala implementation for that problem.
Here it is the automatic test (in BDD style with ScalaTest)
import org.scalatest._
class RichStringSpec extends FlatSpec with MustMatchers {
"A rich string" should "find the longest run of consecutive characters" in {
import Example._
"abceedd".longestRun mustBe Set("ee", "dd")
"aeebceeedd".longestRun mustBe Set("eee")
"aaaaaaa".longestRun mustBe Set("aaaaaaa")
"abcdefgh".longestRun mustBe empty
}
}
Following is the imperative style implementation, with nested loops and mutable variables as you would normally choose to do in Java or C++:
object Example {
implicit class RichString(string: String) {
def longestRun: Set[String] = {
val chunks = mutable.Set.empty[String]
val ilen = string.length
var gmax = 0
for ((ch, curr) <- string.zipWithIndex) {
val chunk = mutable.ListBuffer(ch)
var next = curr + 1
while (next < ilen && string(next) == ch) {
chunk += string(next)
next = next + 1
}
gmax = chunk.length max gmax
if (gmax > 1) chunks += chunk.mkString
}
chunks.toSet.filter( _.length == gmax )
}
}
}
Following is a functional-style implementation, hence no variables, no loops but tail recursion with result accumulators and pattern matching to compare each character with the next one (Crazy! Isn't it?):
object Example {
implicit class RichString(string: String) {
def longestRun: Set[String] = {
def recurse(chars: String, chunk: mutable.ListBuffer[Char], chunks: mutable.Set[String]): Set[String] = {
chars.toList match {
case List(x, y, _*) if (x == y) =>
recurse(
chars.tail,
if (chunk.isEmpty) chunk ++= List(x, y) else chunk += y,
chunks
)
case Nil =>
// terminate recursion
chunks.toSet
case _ => // x != y
recurse(
chars.tail,
chunk = mutable.ListBuffer(),
chunks += chunk.mkString
)
}
}
val chunks = recurse(string, mutable.ListBuffer(), mutable.Set.empty[String])
val max = chunks.map(_.length).max
if (max > 0) chunks.filter( _.length == max ) else Set()
}
}
}
For example, for the given "aeebceeedd" string, both implementations above will build the following set of chunks (repeating characters)
Set("ee", "eee", "dd")
and they will filter those chunks having the maximum length (resulting "eee").
This code should work for any length of string sequence.
public class LongestStringSequqnce {
static String myString = "aaaabbbbcccchhhhiiiiibbbbbbbbbccccccc";
static int largestSequence = 0;
static char longestChar = '\0';
public static void main(String args[]) {
int currentSequence = 1;
char current = '\0';
char next = '\0';
for (int i = 0; i < myString.length() - 1; i++) {
current = myString.charAt(i);
next = myString.charAt(i + 1);
// If character's are in sequence , increase the counter
if (current == next) {
currentSequence += 1;
} else {
if (currentSequence > largestSequence) { // When sequence is
// completed, check if
// it is longest
largestSequence = currentSequence;
longestChar = current;
}
currentSequence = 1; // re-initialize counter
}
}
if (currentSequence > largestSequence) { // Check if last string
// sequence is longest
largestSequence = currentSequence;
longestChar = current;
}
System.out.println("Longest character sequence is of character "
+ longestChar + " and is " + largestSequence + " long");
}
}
Source : http://www.5balloons.info/program-java-code-to-find-longest-character-sequence-in-a-random-string/
if(ctr>ctrstor){
output=i;
}
//storing purposes
ctrstor=ctr;
This looks like the problem. So if you find 8 consecutive characters, it will set output to 8, and proceed. The next time thru, it finds 3 consecutive characters, so doesn't set output, but sets ctrstor. Next time thru it finds 4 consecutive characters, and this will set output to 4
There are few traps in the code that your logic felt in:
Code incorrectly assumes that there is always next character to compare current one.
This fails for string like "a" or the last character in any string.
Code does not store the max count of characters but only the max index (i).
MaxCount is needed to compare the next chars sequence size.
Loop for and loop while repeat the same subset of characters.
Also variable name style makes it harder to understand the code.
After correcting above
public static int runLongestIndex(String setofletters) {
int maxCount = 0;
int maxIndex = 0;
// loops each character in the string
for (int i = 0; i < setofletters.length() - 1; ) {
// new char sequence starts here
char currChar = setofletters.charAt(i);
int count = 1;
int index = i;
while ( (index < setofletters.length() - 1) &&
(currChar == setofletters.charAt(++index)) ) {
count++;
}
if (count > maxCount) {
maxIndex = i;
maxCount = count;
}
i = index;
}
return maxIndex;
}
See Java DEMO
I think you don't need an internal loop:
public static int runLongestIndex(String setofletters) {
if (setofletters == null || setofletters.isEmpty()) {
return -1;
}
int cnt = 1;
char prevC = setofletters.charAt(0);
int maxCnt = 1;
//char maxC = prevC;
int maxRunIdx = 0;
int curRunIdx = 0;
for (int i = 1; i < setofletters.length(); i++){
final char c = setofletters.charAt(i);
if (prevC == c) {
cnt++;
} else {
if (cnt > maxCnt) {
maxCnt = cnt;
//maxC = prevC;
maxRunIdx = curRunIdx;
}
cnt = 1;
curRunIdx = i;
}
prevC = c;
}
if (setofletters.charAt(setofletters.length() - 1) == prevC) {
if (cnt > maxCnt) {
//maxC = prevC;
maxCnt = cnt;
maxRunIdx = curRunIdx;
}
}
return maxRunIdx;
}
and this code:
System.out.println(runLongestIndex("aaakkcccccczz"));
gives you
5
This is how a "colleague" of mine is understanding to write readable code in order to solve this problem, even if this is working :)
public static int count (String str) {
int i = 0;
while(i < str.length()-1 && str.charAt(i)==str.charAt(i+1))
i ++;
return ++i;
}
public static int getLongestIndex(String str){
int output = 0;
for(int i=0, cnt = 1, counter = 0 ; i<str.length() - 1;i += cnt, cnt = count(str.substring(i)), output = (counter = (cnt > counter ? cnt : counter)) == cnt ? i : output);
return output;
}
int indexOfLongestRun(String str) {
char[] ar = str.toCharArray();
int longestRun = 0;
int lastLongestRun = 0;
int index = 0;
for(int i = ar.length-1; i>0; i--){
if(ar[i] == ar[i-1]){
longestRun++;
}else{
if(longestRun > lastLongestRun){
lastLongestRun = longestRun;
longestRun = 0;
index = i;
}
}
}
return index;
Well, the solution a bit depends on the additional requirements. Here is the code which returns the FIRST longest sequence of a repeated character int the given string, meaning if you have a second sequence with the same length you never get it out :(. But still, this is a simple and clear solution here, so good news - it works! :)
string = 'abbbccddddddddeehhhfffzzzzzzzzdddvyy'
longest_sequence = ''
for i in range(len(string)):
is_sequence = True
ch_sequence = ''
while is_sequence:
ch_sequence += string[i]
if i+1 < len(string) and string[i]==string[i+1]:
i += 1
else:
is_sequence = False
if len(ch_sequence) > len(longest_sequence):
longest_sequence = ch_sequence
print (longest_sequence)
#Paolo Angioletti already provided an answer using Scala, but it's more complicated than it needs to be. The idea is not very different from Run-length encoding. Time complexity O(n).
def longestConsecutive(s: String): (Char, Int) = {
Iterator.iterate(('\u0000', 0, 0)) { case (ch, longestRun, i) =>
val run = (i until s.length)
.takeWhile(s(_) == s(i))
.size
if (run > longestRun) (s(i), run, i + run)
else (ch, longestRun, i + run)
}
.dropWhile(i => s.isDefinedAt(i._3))
.take(1)
.map(x => (x._1, x._2))
.next()
}
Tested with:
("s", "ch", "n")
----------------
("", '\u0000', 0),
("a", 'a', 1),
("aabcddbbbea", 'b', 3),
("abcddbbb", 'b', 3),
("cbccca", 'c', 3)
#include <iostream>
#include<algorithm>
using namespace std;
int main() {
string s="abbcccccbbffffffffff";
//cin>>s;
int count=1;
int maxcount=1;
int start=0;
int ps=0;
for (int i=0;i<s.size()-1;i++)
{
if(s.at(i)==s.at(i+1))
{
count +=1;
maxcount=max(maxcount,count);
}
else
{
ps=max(ps,start+count);
count =1;
start=i;
}
}
for(int i=1;i<=maxcount;i++)
{
cout<<s.at(i+ps);
}
// your code goes here
return 0;
}
This is the simplest I can think of and it will print the number of the longest sequenced identical characters in a one line string.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine();
scanner.close();
int count = 0;
int curCount = 1;
for (int i = 0; i < s.length() -1; i++) {
if (s.charAt(i) == s.charAt(i + 1)) {
curCount++;
if (curCount > count) {
count = curCount;
}
}else {
if (curCount > count) {
count = curCount;
}
curCount = 1;
}
}
System.out.println(count);
}
I have a code that must print only vowels from my strings in the array list but I'm not sure if I'm doing it right in my method. How do I resolve this? Its only printing out 5 of them because I'm not sure how to directly get each specific vowels. Please find the below code that I have tried.
import java.util.*;
public class vowels {
public static void main(String[] args) {
ArrayList<String> vowels = new ArrayList<String>();
vowels.add("mitsubishi");
vowels.add("subaru");
vowels.add("nissan");
vowels.add("honda");
vowels.add("toyota");
averageVowels(vowels);
}
public static void averageVowels(ArrayList<String> vowels) {
System.out.println(vowels);
int number = 0;
for (int i = 0; i < vowels.size(); i++)
{
if (vowels.get(i).contains("a") || vowels.get(i).contains("e") || vowels.get(i).contains("i") ||vowels.get(i).contains("o") || vowels.get(i).contains("u"))
{
number++;
}
}
System.out.println("a count: " +number);
System.out.println("e count: " +number);
System.out.println("i count: " +number);
System.out.println("o count: " +number);
System.out.println("u count: " +number);
}
}
You can do without any loops, quite easily so
public static void averageVowels(ArrayList<String> vowels) {
System.out.println(vowels);
String arrayToString = vowels.toString();
int length = arrayToString.length();
System.out.println("a count: " + (length - arrayToString.replace("a", "").length()));
System.out.println("e count: " + (length - arrayToString.replace("e", "").length()));
System.out.println("i count: " + (length - arrayToString.replace("i", "").length()));
System.out.println("o count: " + (length - arrayToString.replace("o", "").length()));
System.out.println("u count: " + (length - arrayToString.replace("u", "").length()));
}
It prints
[mitsubishi, subaru, nissan, honda, toyota]
a count: 4
e count: 0
i count: 4
o count: 3
u count: 3
You want to count five types of things, so you need five variables:
int aCount = 0;
int eCount = 0;
int iCount = 0;
int oCount = 0;
int uCount = 0;
There are many different ways you could loop through each of the words, and then each of the characters in each of the words. Here's one way:
for (int i = 0; i < vowels.size(); i++) {
String lowerCaseWord = vowels.get(i).toLowerCase(); //get lowercase version so we don't have to check each letter twice
for (int j=0; j<lowerCaseWord.length(); j++){ //loop through each char in the string
char c = lowerCaseWord.charAt(j);
if (c == 'a') aCount++;
else if (c == 'e') eCount++;
else if (c == 'i') iCount++;
else if (c == 'o') oCount++;
else if (c == 'u') uCount++;
}
}
Make 5 different variables to count the number of the vowel. For example numbera, number e etc. Then you will need 5 if statements (one for each vowel) each of which will increase its respective count by 1.
for (int i = 0; i < vowels.size(); i++)
for (int j = 0; j<vowels.get(j).length(); j++) {
if (vowels.get(i).charAt('a'))
{
numbera++;
}
if (vowels.get(i).charAt('e'))
{
numbere++;
}
if (vowels.get(i).charAt('i'))
{
numberi++;
}
if (vowels.get(i).charAt('o'))
{
numbero++;
}
if (vowels.get(i).charAt('u'))
{
numberu++;
}}
This
if (vowels.get(i).contains("a") || vowels.get(i).contains("e") || vowels.get(i).contains("i") ||vowels.get(i).contains("o") || vowels.get(i).contains("u"))
only checks if the string contains a, e, i, o, or u. If it found one of these, it won't bother to check the rest of the string. And since you are using ||, in your if statement, it will not evaluate the next conditions if the current condition is already true, so it will proceed to increment number.
If you want to find the number of each vowel, One way is to loop through the string by turning it into a char array and check if a character is a vowel. Then you should create a counter for each vowel and a separated if/switch statement for each. For example with an if statement.
int aCount = 0;
int eCount = 0;
int iCount = 0;
int oCount = 0;
int uCount = 0;
for (int i = 0; i < vowels.size(); i++) {
for (char c : vowels.get(i).toCharArray()) {
if (c == 'a') {
aCount++;
} else if (c == 'e') {
eCount++;
} else (c == 'i') {
iCount++;
} else if (c == 'o') {
oCount++;
} else if (c == 'u') {
uCount++;
} else {
continue;
}
}
}
The following implementation will be efficient. Maintaining a single char array of size 256 would be good enough, which works not only for vowels but for any ASCII character.
import java.util.*;
public class Vowels {
public static void main(String[] args) {
ArrayList<String> vowels = new ArrayList<String>();
vowels.add("mitsubishi");
vowels.add("subaru");
vowels.add("nissan");
vowels.add("honda");
vowels.add("toyota");
averageVowels(vowels);
}
public static void averageVowels(ArrayList<String> vowels) {
System.out.println(vowels);
int[] chars = new int[256];
int number = 0;
for (int i = 0; i < vowels.size(); i++)
{
for (char c : vowels.get(i).toCharArray()) {
chars[c]++;
}
}
System.out.println("a count: " +chars['a']);
System.out.println("e count: " +chars['e']);
System.out.println("i count: " +chars['i']);
System.out.println("o count: " +chars['o']);
System.out.println("u count: " +chars['u']);
}
}
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