Counting vowels in a string - java

I got 3 strings from the user as input.Then count the vowels in each word and print as follows.If the vowel count = 0 and 1 then print 0.If the vowel count = 2 then print 2.If the vowel count is greater than or equal to 3 then print 3.
I tried this code.
Scanner in = new Scanner(System.in);
String[] str = new String[3];
for (int i = 0; i<3; i++)
str[i] = in .nextLine();
for (int j = 0; j<3; j++) {
String s1 = str[j];
String s = s1.toLowerCase();
int count = 0;
for (int i = 0; i<s.length(); i++)
{
if (s.charAt(i) == 'a' || s.charAt(i) == 'e' || s.charAt(i) == 'i' || s.charAt(i) == 'o' || s.charAt(i) == 'u') {
count++;
}
if (s.charAt(i) == ' ') {
if (count == 0||count == 1) {
System.out.print("0");
} else if (count == 2) {
System.out.print("1");
} else {
System.out.print("3");
}
count = 0;
}
}
if (count == 0||count == 1) {
System.out.println("0");
} else if (count == 2) {
System.out.println("1");
} else {
System.out.println("3");
}
}
But there is one condition only print the vowel count for 3 words only even if the user enter the string with more than 3 words.For eg if the user gives the string "hi hello all, how are you,I am fine and u" it prints "010
011
001" like this only but this code prints as "010
011
00100".Now how can i change the code to print the vowel count only for 3 words and not for more than 3?

You need some kind of a break after the third word. One option would be to make an extra variable for tracking it and increment it when the character is space. After 3 words you could break the loop.
Other option would be to split the String into words with split() method and the iterate over the first 3 only.

You could simplify your code a lot and it will be easier to achieve what you want. Instead of loop on each char, you can split your string. And then loop on the words. Something like this:
for (int j = 0; j<3; j++) {
String[] words = str[j].toLowerCase().split(" ");
// Use Math.min, thanks that it works even if you have only 2 words
for(int i = 0; i < Math.min(3, words.length()); i++) {
int count = 0;
for (char letter : words[i].toCharArray()) {
// if letter is vowel: count += 1;
}
// System.out.println depending on count value
}
}

You could use a Regex to split words into a sentence, using this method:
String[] splits = myPhrase.split(" ");
to split words in a sentence, but you have to be careful that if the user enters more spaces, the first one is "eliminated" and those just after end up in the split.
For example:
String phrase = "1 2 3 z";
String[] splits = phrase.split(" ");
generates this array: [1|2| |3| | |z].
So, in my opinion, at that point you could use a filter, go through the array / list again eliminating any space derived from the regex or more simply when you scroll through the array / list and find a space you don't consider it.
At this point go to analyze the first 3 elements of the array / list, discarding the others (maybe using a counter).
Finally, again using a Regex, you can also check if the character you are analyzing is a vowel or not using this command:
if (s.charAt(i).matches("[AEIOUaeiou]")){ /*it's a vowel*/}

Related

Position of every vowel in a String [duplicate]

I'm a beginner in Java and I have a question regarding loops. I've been struggling with this task where it says: Write programs that read a line of input as a string and print the positions of all vowels in the string.
I have managed to print out the number of vowels in the input but I got stuck when it came to print out their positions.
Any help would be appreciated!
System.out.println("Enter your input: ");
String input = in.nextLine();
int sum = 0;
for(int i = 0; i < input.length(); i++){
char vowel = input.charAt(i);
if(vowel == 'a'|| vowel == 'e'|| vowel == 'i'||
vowel == 'o'|| vowel == 'u'|| vowel == 'y'){
sum++;
}
}
System.out.println(sum);
System.out.println("Enter your input: ");
String input = in.nextLine();
int sum = 0;
for(int i = 0; i < input.length(); i++){
char vowel = input.charAt(i);
if(vowel == 'a'|| vowel == 'e'|| vowel == 'i'||
vowel == 'o'|| vowel == 'u'|| vowel == 'y'){
sum++;
System.out.println("position ->"+i);//added line
}
}
System.out.println(sum);
you just needed to add single line that prints the positions
Avoid char
The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most of the >144,000 characters defined in Unicode.
Code point
To work with individual characters, use code point integer numbers.
Define your set of targeted vowels. Sort the array, so that we may search quickly via binary search.
int[] vowelCodePoints = "aeiouy".codePoints().sorted().toArray() ;
Get the code points of the characters in your input.
int[] codePoints = "test".codePoints().toArray() ;
Loop the array of code points of our input string, by index (zero-based counting). Test each code point to see if it is found within our array of vowel code points.
To go in the reverse direction, from code point integer to the character as text, call Character.toString.
Example code
Pull all the code together.
int[] vowelCodePoints = "aeiouy".codePoints().sorted().toArray();
int[] codePoints = "testy".codePoints().toArray();
List < Integer > indicesOfVowels = new ArrayList <>( codePoints.length );
for ( int index = 0 ; index < codePoints.length ; index++ )
{
int position = Arrays.binarySearch( vowelCodePoints , codePoints[ index ] );
if ( position >= 0 )
{
String vowel = Character.toString( codePoints[ index ] );
System.out.println( "Vowel: " + vowel + " | Index: " + index );
}
}
See this code run at Ideone.com.
Vowel: e | Index: 1
Vowel: y | Index: 4

Write programs that read a line of input as a string and print the positions of all vowels in the string

I'm a beginner in Java and I have a question regarding loops. I've been struggling with this task where it says: Write programs that read a line of input as a string and print the positions of all vowels in the string.
I have managed to print out the number of vowels in the input but I got stuck when it came to print out their positions.
Any help would be appreciated!
System.out.println("Enter your input: ");
String input = in.nextLine();
int sum = 0;
for(int i = 0; i < input.length(); i++){
char vowel = input.charAt(i);
if(vowel == 'a'|| vowel == 'e'|| vowel == 'i'||
vowel == 'o'|| vowel == 'u'|| vowel == 'y'){
sum++;
}
}
System.out.println(sum);
System.out.println("Enter your input: ");
String input = in.nextLine();
int sum = 0;
for(int i = 0; i < input.length(); i++){
char vowel = input.charAt(i);
if(vowel == 'a'|| vowel == 'e'|| vowel == 'i'||
vowel == 'o'|| vowel == 'u'|| vowel == 'y'){
sum++;
System.out.println("position ->"+i);//added line
}
}
System.out.println(sum);
you just needed to add single line that prints the positions
Avoid char
The char type has been essentially broken since Java 2, and legacy since Java 5. As a 16-bit value, char is physically incapable of representing most of the >144,000 characters defined in Unicode.
Code point
To work with individual characters, use code point integer numbers.
Define your set of targeted vowels. Sort the array, so that we may search quickly via binary search.
int[] vowelCodePoints = "aeiouy".codePoints().sorted().toArray() ;
Get the code points of the characters in your input.
int[] codePoints = "test".codePoints().toArray() ;
Loop the array of code points of our input string, by index (zero-based counting). Test each code point to see if it is found within our array of vowel code points.
To go in the reverse direction, from code point integer to the character as text, call Character.toString.
Example code
Pull all the code together.
int[] vowelCodePoints = "aeiouy".codePoints().sorted().toArray();
int[] codePoints = "testy".codePoints().toArray();
List < Integer > indicesOfVowels = new ArrayList <>( codePoints.length );
for ( int index = 0 ; index < codePoints.length ; index++ )
{
int position = Arrays.binarySearch( vowelCodePoints , codePoints[ index ] );
if ( position >= 0 )
{
String vowel = Character.toString( codePoints[ index ] );
System.out.println( "Vowel: " + vowel + " | Index: " + index );
}
}
See this code run at Ideone.com.
Vowel: e | Index: 1
Vowel: y | Index: 4

how to take into account the presence of more than one space? java

Task: There is a string. Calculate the number of words in the string. The word is considered separated by spaces. (You can not use regular expressions)
How to solve? If you enter two or more spaces in a row - will consider that these words but I need to count as one big pass between the words
Example I_live_in_Lviv - 4 words, but if we put one more space (for an example before Lviv) -> I_live_in__Lviv - 5 words (instead of underlining, put a space(-s))
Scanner in = new Scanner(System.in);
String line = in.nextLine();
int n = 0;
if (line.length() != 0) {
n++;
for (int i = 0; i < line.length(); i++) {
if (line.charAt(i) == ' ') {
n++;
}
}
}
System.out.print(n);
Answer:
Scanner in = new Scanner(System.in);
String line = in.nextLine();
int count = 0;
for(int i = 0; i <= line.length() - 1; i++){
if(Character.isLetter(line.charAt(i))){
count++;
for( ; i <= line.length() - 1; i++){
if(line.charAt(i) == ' '){
i++;
break;
}
}
}
}
System.out.print(count);
in.close();
Result:
I_live_in__Lviv_ - 4
So from what I'm understanding you have a string, e.g. " hi my name is Matthew" and you want to find how many words are in the string. I would just take two characters at a time, but step them by one, and test if the first is a space and the second isn't. So take " h", that's the beginning of a word. Then "hi", that's not, etc. Of course you'd want to check if the first character isn't a space and if not increment the word count.
Edit: Sorry I didn't elaborate, I was in a time crunch this morning. Use String.subString(i, i + 2); to get two characters from the string. Then check the new string with either subString() or charAt() (I'd recommend charAt()), of course accounting for the string length - 2 to prevent an error being thrown.
for (int i = 0; i < exampleString.length - 2; i++) {
//subtract 2 to prevent subString from throwing an error
if ((exampleString.subString(i, i + 2).charAt(1) = " " && exampleString.subString(i, i + 2).charAt(2) != " ") || i = 0) {
//add 2 to get a space and a letter, then test the first character for a
//space and the second character for NOT a space, also increment words if
//i = 0, presuming there is no space at the beginning of the string
words++;
}
}
So basically what #JB Nizet said, only in answer form... sorry I didn't see your comment until now, I wouldn't have typed all of this
just add one more variable and store the previous character in it. Check if it is space with the next character if it returns false increment the count.
Scanner in = new Scanner(System.in);
String line = in.nextLine();
int count = 0;
for(int i = 0; i <= line.length() - 1; i++){
if(Character.isLetter(line.charAt(i))){
count++;
for( ; i <= line.length() - 1; i++){
if(line.charAt(i) == ' '){
i++;
break;
}
}
}
}
System.out.print(count); //I_live_in__Lviv_ - 4
in.close();

StringIndexOutOfBoundsException while counting special characters a string

I was writing a code that counts special characters in a string prompt from the key board. This is the method.
public static int specislChar(String s){
int counter = 0;
char ch;
for (int i =0 ; i<=s.length(); i++){
ch = s.charAt(i);
if (!Character.isLetterOrDigit(ch) || ch != ' ') {
System.out.print(" " + ch);
counter++;
}
}
return counter;
}
Every time I call this method, at the System.out.print() it gives me an error:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException:
String index out of range: 20
your loop should be less than i<s.length(). it is the cause of StringIndexOutOfBoundsException and you have to use AND operator not OR
for (int i = 0; i < s.length(); i++) {
ch = s.charAt(i);
if (!Character.isLetterOrDigit(ch) && !Character.isSpaceChar(ch)) {
System.out.print(" " + ch);
counter++;
}
}
When debugging this kind of issues, always run you code step by step and check if what you wrote is doing what you expect at every step, it's a simple but invaluable technique :)
If you want to count chars that are not letter/digit/space, this:
|| ch != ' '
will always give true for every character that is not space, the check you need to to is this one:
if ( !(Character.isLetterOrDigit(ch) || (ch==' ')) ){
Or, applying De Morgan's Law:
if ( (!Character.isLetterOrDigit(ch)) && (ch!=' ') ){
The error you are getting is due to this line: for (int i =0 ; i<=s.length(); i++){. In Java, arrays are 0 based and run from 0 to n-1, where n is the amount of entries you have.
Thus, changing it to for (int i =0 ; i<s.length(); i++){ will remove the error.
Also, this: || ch != ' ' will be true for any non special character as well, which will cause inaccurate results. I think you mean && ch != ' '.
Example code:
public class ____QuickTester {
public static void main(String[] args) {
// This should be 11
System.out.println("Number of special characters: " +
specialChar("asdaskd12312!#(#(!##)(*asdas12301230"));
// This should be 8
System.out.println("Number of special characters: " +
specialChar("!a#b#c$d%e aaa bbb ccc !!!"));
}
public static int specialChar(String s) {
// Get rid of alphabets, digits and space
s = s.replaceAll("[A-Za-z0-9 ]", "");
return s.length();
}
}
Output:
Number of special characters: 11
Number of special characters: 8
A much simpler way would be to remove all alphabets, digits, and space
The remaining content will be the special characters
Change your for loop condition from <= to < to solve StringIndexOutOfBoundsException as array index start from 0 so it will go upto length-1.
i < s.length();
And use &&(And) operator instead of ||(Or) operator in if condition as you want to check both the conditions.
if (!Character.isLetterOrDigit(ch) && !Character.isSpaceChar(ch) )
Do something like this :-
public static int specislChar(String s) {
int counter = 0;
for (char ch : s.toCharArray())
if (!Character.isLetterOrDigit(ch) && ch != ' ')
counter++;
return counter;
}
Input :- %#%^&*(hi hello$!!+ #
Output :- 12
you are looping though i<=s.length(); but it should be i<=s.length()-1; because index starts at 0. If it starts at 0 then it should be only to length-1

Find first non repeating character without using hashmap

I wanted to find first non repeating character in a string. I wrote the following function in which I am stuck at one point. Google tells me the hashmap method for this but I'll be grateful if someone could help me with my code.
public static Character firstNonRepeatedChar(String line) {
Character c = null;
int strLength = line.length();
for (int i =0; i<strLength-1; i++){
int flag = 0;
for(int j = i+1; j<strLength-i; j++){
if(line.charAt(i) == line.charAt(j)){
flag++;
break;
}
else
continue;
}
if (flag==0){
c = line.charAt(i);
break;
}
}
return c;
}
}
Problem : How can I put a check that the repeating character that is already checked once is not checked again.
Ex: If my string is "hhello" then the code first compares the h at index 0 with all the other characters. Since its repeating the next iteration of outer for loop starts in which i now points to index 1 of the string i.e the repeating h and compares it with the rest of elements. Since it does not get a repeating instance it returns 'h' as non repeating character which is wrong.
How can I fix this? Is there any way?
Pls help
EDIT: Repeating character need not be the immediate next character.
Ex: In string "helloWorld" characters 'l' and 'o' are repeating.
In string "hehelo" characters 'h' and 'e' are repeating and first non repeating character will be 'l'
***For all case of repetition
Character c = null;
int strLength = line.length();
for (int i = 0; i < strLength; i++) {
int flag = 0;
for (int j = 0; j < strLength; j++) {
if (line.charAt(i) == line.charAt(j) && i != j) {
flag = 1;
break;
}
}
if (flag == 0) {
c = line.charAt(i);
break;
}
}
return c;
This is so simple to check, Your logic is complex. try this for immediate repeated character.
Character c = null;
int strLength = line.length();
for (int i = 0; i < strLength - 1;) {
int flag = 0;
int present_char_position = 0;
if (line.charAt(i) == line.charAt(i + 1)) {
flag++;
present_char_position = i;
i += 2;//jumping from those two character if matched
continue;
} else {
present_char_position = i;
i++;//if not matched go to next character
}
if (flag == 0) {
c = line.charAt(present_char_position);
break;
}
}
return c;
Hint 1: A repeating character1 is one that is the same as the previous character in the String. A non-repeating character is .........
Implement that!
Hint 2: You don't need a nested loop.
UPDATE
I see. So you are using "non-repeating character" to mean something different to what most people would mean. What you are actually looking for is the first character that appears only once in the entire string.
Anyway ... at least I now understand why you are using a nested loop now, and I understand the bug.
Hint 3: Even when a character appears multiple time in a string, it will still appear ZERO times after its last occurrence.
That is what your inner loop tests for. So what you are finding is the first character in the string that isn't duplicated in the remainder of the string.
The fix is simple ... once you understand what you are doing wrong.
Once you have fixed that are some other tidy ups:
The else continue is redundant.
The c variable is unnecessary ... if you change:
if (flag==0){
c = line.charAt(i);
break;
}
to
if (flag==0){
return line.charAt(i);
}
and
return c;
to
return null;
1 - This is what a native English speaker understands by "find the first non-repeating character". It is possible that you mean something else. If so, please update the question to clarify. Please describe as clearly as you can what you mean. Please give examples.
The easiest way to flag doublets would be to replace the characters with a none printable one. You can then skip these positions. But this will add another O(n) to your loop replacing the characters. The worst case would result in O(n^3). Optimizing you could write an inner loop replacing only the characters ahead of your current position. This would result in a O(n^2) again, because currently you have O(n^2) (n*n/2).
UPDATE
Added code and fixed a bug, where the non repeating character is at last position of the String.
Instead of processing the String, now processing the char[].
private static final char FLAG = '\u0000';
public static Character firstNonRepeatedChar(String line)
{
final char[] chars = line.toCharArray();
Character c = null;
final int strLength = chars.length;
for (int i = 0; i < strLength; i++)
{
if (chars[i] == FLAG)
{
continue;
}
int flag = 0;
for (int j = i + 1; j < strLength; j++)
{
if (chars[i] == chars[j])
{
flag++;
chars[j] = FLAG;
}
}
if (flag == 0)
{
c = chars[i];
break;
}
}
return c;
}
Below method will return you what you are looking.
public static char getFirstNonRepeatedChar(String input) {
char c = 0;
for (int i =0; i<input.length(); i++){
int flag = 0;
for(int j = 0; j<input.length(); j++){
if(input.charAt(i) == input.charAt(j)){
flag++;
}
if(flag>1)
break;
}
if (flag == 1){
c = input.charAt(i);
break;
}
}
return c;
}
This one is for PHP
<?php
$string = "ABBGAACCE";
$stringArray = str_split($string); // string converted to array
$temp_array = [];
$non_repeating_array = get_first_non_repeating($stringArray, $temp_array);
echo reset($non_repeating_array); // display first non repeating character from string
function get_first_non_repeating($stringArray, $temp_array)
{
$repeating = []; // store all repeating characters
foreach($stringArray as $key => $char)
{
if(array_key_exists($char, $temp_array)) // check if character was already saved meaning it is repeating
{
array_push($repeating, $char); // push all repeating character in a variable
$stringArray = array_diff($stringArray, $repeating); // subtract repeating characters from the string array
}else{
$temp_array[$char] = 1;
}
}
return $stringArray; // returns the non repeating characters
}

Categories

Resources