This question already has answers here:
How do I count the number of occurrences of a char in a String?
(48 answers)
Closed 7 years ago.
I am trying to count the amount of 'x' characters that are in a string, and print out the number. I end up just counting the number of characters in the string instead. Here is what I have tried:
int count = 0;
for (int j = 0; j < input1.length(); j++)
{
char character = input1.charAt(j);
count++;
}
if (indexX != -1)
{
System.out.println("x count: "+count);
} // indexX = input1.indexOf('x');
You are not checking if the chacter is x, and then increasing the counter.
if(character == 'x')
counter++;
You never check what the character is.
char character = input1.charAt(j);
if (character == 'x') {
count++;
}
You need to check if the character is 'x'.
This is how you do it :
for (int j = 0; j < input1.length(); j++)
{
char character = input1.charAt(j);
if (character == 'x' || character == 'X') {
count++;
{
}
How about comparing length of string pre and post replace, have a look at http://www.rosettacode.org/wiki/Count_occurrences_of_a_substring#Java
Common method that would work everywhere.
Related
Here is the code I wrote in Java to count vowels (a, e, i, o, u, y) in n strings:
import java.util.*;
import java.io.*;
public class VowelCount {
public static void main(String[] args) {
Scanner x = new Scanner(System.in);
int n = x.nextInt();
int[] count = new int[n];
for(int i = 0; i < n; i++) {
if(x.hasNextLine()) {
String str = new String(x.nextLine());
int counter = 0;
for(int j = 0; j < str.length(); j++) {
char ch = str.charAt(j);
if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' || ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U' || ch == 'y' || ch == 'Y') {
counter += 1;
}
}
count[i] = counter;
}
}
for(int k = 0; k < n; k++) {
System.out.print(count[k] + " ");
}
}
}
If I insert 10 strings like:
(hello, hi, string, int, double, boo, ad, ok, def, rep)
it should return
2 1 1 1 3 2 1 1 1 1
but what it returns is
0 2 1 1 1 3 2 1 1 1
so it count the first one as the second and doesn't count the last one (in fact right after writing "def" in the console it runs the code and prints the solution in console.
Can you help me figure it out where I am wrong? It would be really appreciated, thanks!
This looks like standard hackerrank format. I believe most of the templates include code to read the data - if one problem doesn't, just copy code from one that does.
I'm guess the problem here is that nextInt does not read the line ending. The first nextLine just reads the newline after the count.
int n = x.nextInt();
int[] count = new int[n];
for(int i = 0; i < n; i++) {
if(x.hasNextLine()) {
String str = new String(x.nextLine());
The method .nextInt() doesn't finish to read all the line, so your first call to x.nextLine() catch the space after the int.
Just add a line after : x.nextLine();
int n = x.nextInt();
int[] count = new int[n];
x.nextLine();
This question already has answers here:
Java charAt() String index out of range: 0
(5 answers)
How do I compare strings in Java?
(23 answers)
Closed 3 years ago.
Hi I keep getting this error whenever I try to input an empty String. Everything else so far works and if I put a space inside the String it works. I know this is really picky but I'm super curious what I should do in this situation to make sure it returns just an empty String.
**> HW2.nthWord(2,"")
java.lang.StringIndexOutOfBoundsException: String index out of range: 0
at java.lang.String.charAt(Unknown Source)
at HW2.nthWord(HW2.java:124)**
I did create a special instance for when this value is put in but it still does not work.
What do I need to to correct this?
/*nthWord takes an int and a String as input and returns a String:
The input int represents a number n that is assumed to be positive, and the output string
contains every nth word of the input string, starting with the first word, separated by a single space.
For this method, a word is defined to be a sequence of non-space characters.
There should be no space at the end of the output string.
*/
public static String nthWord( int number, String input ){
StringBuilder create = new StringBuilder();
int totalspaces = 0; //This is to hold a count of the number of spaces in a String
if( number == 0){
return input;
}
if(input == ""){
return input;
}
else{
for(int i = 0; input.charAt(i) != ' '; i = i + 1){
create.append(input.charAt(i));
}
for( int i = 0; i < input.length() - 1 ; i = i + 1){
if(input.charAt(i) == ' ' && i < input.length() - 1 && input.charAt(i+1) != ' '){
if( i != input.length()-1 && input.charAt(i+1) != ' '){
totalspaces = totalspaces + 1;
}
if(totalspaces % number == 0 && totalspaces != 0){
create.append(' ');
for(int j = i+1; input.charAt(j) != ' ' && j < input.length(); j = j+1){
create.append(input.charAt(j));
i = j;
}
}
}
}
return create.toString();
}
}
I noticed a few things
for(int i = 0; input.charAt(i) != ' '; i = i + 1){
create.append(input.charAt(i));
}
This loops will keep adding characters of "input" until it reaches a space' ' character. If input does not have a space character then this loop will go beyond the length of input and cause the error. You may want something like:
for(int i = 0; i < input.length(); i = i + 1){
if(input.charAt(i) == ' ' ){
break;
} else {
create.append(input.charAt(i));
}
}
Also, when you get to the line:
if(input.charAt(i) == ' ' && i < input.length() - 1 && input.charAt(i+1) != ' '){
you already know that i < input.length() - 1 because you are in a for loop. You may change that line to:
if(input.charAt(i) == ' ' && input.charAt(i+1) != ' '){
For the same reason, your next section:
if( i != input.length()-1 && input.charAt(i+1) != ' '){
totalspaces = totalspaces + 1;
}
can be changed to
if( i != input.length()-1 ){
totalspaces = totalspaces + 1;
}
Also, I noticed that you may be making the problem harder than it needs to be. The problem will be much easier if you solve it in a single for-loop.
for(int i = 0; i < input.length(); i = i + 1){
if( x ) //x is some code that determines if you are part of the nth word
create.append(input.charAt(i));
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Given a string like:
"all perfect"
my target is to count the score of the words by characters: a=1, b=2, c=3 etc.
but if I found two indentical consecutive letters form into the word (ll for all), the score it will be multiplicate for 2.
Now i have make this code to calculate a linear word:
for (char ch : str.toCharArray()) {
if (ch >= 'A' && ch <= 'Z') {
sum += 1 + ch - 'A';
System.out.printf("The sum of %s is %d%n", str, sum);
how can I count the value of the word if it is given by input? I used to split the String previously.
String[] arr = str.split(" ");
int sumDupicate = consecutiveLetters(arr);
I have some issues here when I try to do the method:
public static int consecutiveLetters(String[] arr) {
for (int i = 0; i < arr.length; i++) {
int j;
int sum = 0;
char ch1, ch2;
for (j = 1; j < arr[i].length(); j++) {
ch1 = arr[i].charAt(j);
ch2 = arr[i].charAt(j - 1);
if (ch1 == ch2) {
//obviously this sum, count is wrong
sum += ((int) arr[i] -96)*2;
}
EDIT:
If I have the sentence:
aabbcc
the algorthm needs to give the score: 96
because:
aabbcc =
double 12 * 2 = 24,
double it again = 24 *2 = 48
double it again = 48 * 2 = 96
a word's score is doubled for every adjacent pair of letters is contains.
I hope now is clear my request.
public static int consecutiveLetters(String[] arr) {
int sum = 0;
for (int i = 0; i < arr.length; i++) {
char ch1, ch2;
double numberOfDuplicates = 0, word = 0;
for (int j = 0; j < arr[i].length()-1; j++) {
ch1 = arr[i].charAt(j);
ch2 = arr[i].charAt(j + 1);
if (ch1 == ch2) {
numberOfDuplicates++;
}
if(Character.isUpperCase(arr[i].charAt(j))) {
word += (int) arr[i].charAt(j) - 64;
} else {
word += (int) arr[i].charAt(j) - 96;
}
}
word += ((int) arr[i].charAt(arr[i].length()-1) - 96);
if(numberOfDuplicates > 0) {
double num = Math.pow(2, numberOfDuplicates);
word = word * num;
}
sum += word;
}
return sum;
}
Input: ["all"]
Output: 25
Input: ["aabbcc"]
Output: 96
Look at having a char that keeps track of the last letter and compare it to the current letter. If they match, then do the multiplication that is needed.
Since you've split the array by spaces already, for each one loop through the String and compare the letter, with the next letter, and return true if found.
public static boolean letterDuplicate(String s) {
boolean check = false;
for (int i = 0; i < s.length() - 1; i++) {
if (s.charAt(i) == s.charAt(i + 1)) {
return true;
}
}
return check;
}
Then do a check if(true), multiply by 2.
I have the following method and I wanted to change the for each loops to normal for loops. So I tried something like this
for (int i = 0; i < above.length(); i++) {
char x = above.toCharArray();
if (x == 'x') {
counter++;
}
}
But I know that's wrong. So, what's the right way to change these for each loops to normal for loops?
public static int neighbourconditions(String above, String same, String below){
int counter = 0;
if(above != null){
for(char x : above.toCharArray()){
if(x == 'x'){
counter++;
}
}
}
for (char x : same.toCharArray()){
if (x == 'x'){
counter++;
}
}
if (below != null){
for(char x : below.toCharArray()){
if (x == 'x'){
counter++;
}
}
}
return counter;
}
Just use a basic for loop whose bounds are governed by the length of the string, which is the same as the size of the corresponding character array, e.g. the first loop:
for (char x : above.toCharArray()) {
if (x == 'x') {
counter++;
}
}
would become this:
for (int x=0; x < above.length(); ++x) {
if (above.charAt(x) == 'x') {
counter++;
}
}
You can use above.toCharArray().length and to get the value above.toCharArray()[i] and with collaboration with #chillworld:
You can create an array of char[] array = above.toCharArray(); outside the loop like this :
char[] array = above.toCharArray();
for (int i = 0; i < array.length; i++) {
if (array[i] == 'x') {
counter++;
}
}
I would imagine that you would have to find the length of each string being passed to the method. Example if the content of above is equal to "some_randome_string" you would have to find the length of the string or how many characters are in the string. in this case that would be 19. then you would do;
if <variable != null > {
for (x = 0; x < 18 ; x++) {
code block to be executed
}
}
If you need to count occurances of character x then you may try below or a regex:
String upAbove = above.replaceAll("x","");
int count = above.length() - upAbove.length();
for (int i = 0; i < str.length(); i ++) // Checks every position of array
{
arr[i] = str.charAt(i); // Ignore this, not needed
if (arr[i] != ',' || arr[i] != '.' || arr[i] != '$') // Checks every position of array to see if any character equals a comma, decimal point, or a dollar sign
{
// Ignore below
/*
valueString = String.valueOf(value);
numOfAsterisks = arr.length - valueString.length();
for (int asterisk = 0; asterisk <= numOfAsterisks; asterisk ++)
{
System.out.print("*");
}
System.out.println((int)value);
*/
}
}
Here, what I want to do is to check an array of characters and see if the array contains a comma, a decimal point, or a dollar sign. If the array does not contain any of these characters, then the commented-out portion (where it says "Ignore below") will be executed. The only problem I have here is that because if (arr[i] != ',' || arr[i] != '.' || arr[i] != '$') is under the outside for loop, the commented-out part is executed multiple times. I need the code to execute only once, but still check each position of the array.
If I understand your question correctly, what you actually want is something like this:
boolean found = false;
for(int i = 0; i < str.length; i++) {
char c = str.charAt(i);
if(c == ',' || c == '.' || c == '$') {
found = true;
break;
}
}
if(!found) {
/* Your commented-out code */
}
Note that this can also be formulated as such:
skip: {
for(int i = 0; i < str.length; i++) {
char c = str.charAt(i);
if(c == ',' || c == '.' || c == '$')
break skip;
}
/* Your commented out code goes here. */
}
Choose for yourself which you like more. :)