How to get indexes of char in the string - java

I want to find vowels positions in the string. How can I make shorter this code?
I tried contains and indexOf method but couldn't do it.
String inputStr = "Merhaba";
ArrayList<Character> vowelsBin = new ArrayList<Character>(Arrays.asList('a', 'e', 'i', 'o', 'u'));
ArrayList<Integer> vowelsPos = new ArrayList<Integer>();
for (int inputPos = 0; inputPos < inputStr.length(); inputPos = inputPos + 1)
for (int vowelPos = 0; vowelPos < vowelsBin.size(); vowelPos = vowelPos + 1)
if (inputStr.charAt(inputPos) == vowelsBin.get(vowelPos)) vowelsPos.add(inputPos);
return vowelsPos;

I assume you want to get m2rh5b7 from your input string Merhaba based on your code, then the below works fine,
String input = "Merhaba";
StringBuilder output = new StringBuilder();
for(int i = 0; i < input.length(); i++){
char c = input.toLowerCase().charAt(i);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
output.append(i+1);
} else {
output.append(c);
}
}
System.out.println(output); // prints --> m2rh5b7
Or if you want just position of the vowels position only, the below is fine,
String input = "Merhaba";
for(int i = 0; i < input.length(); i++){
char c = input.toLowerCase().charAt(i);
if(c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u'){
System.out.println(i);
}
}
you can use regex also, please refer the above from Alias.

Related

Counting vowels in strings in java doesn't count the first string

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();

Efficiency in for loop

How could the following code snippet be optimized? I'm creating space objects to be filled in a 2D array to act as a chess board and am using this to create a more standard naming system.
String name = null;
for(int r = 7; r > -1; r--)
for(int c = 0; c < 8; c++)
{
if(c == 0)
name = "A";
else if(c == 1)
name = "B";
else if(c == 2)
name = "C";
else if(c == 3)
name = "D";
else if(c == 4)
name = "E";
else if(c == 5)
name = "F";
else if(c == 6)
name = "G";
else
name = "H";
final static char[] letters = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H' };
:
for (int c=0; c<8; c++) {
name = letters[c];
:
This has name as a char - does it really need to be a String? If so, make the obvious changes. Define letters as a String[] rather than runtime conversion from char-to-String if you are concerned with efficiency.
You could iterate over characters and change it to a string like this :
for (int r=7; r >= 0; r--) {
for (char c='A'; c <= 'H'; c++) {
name = c + "";
You never finished your for loops, but here is one way to optimize what you have showed us so far:
String name = null;
String letters = "ABCDEFGH";
for (int r=7; r >= 0; r--) {
for (int c=0; c < 8; c++) {
name = letters.charAt(c) + "";
// the rest of your logic
}
}
The ASCII code for 'A' is 65 and for 'H' is 72. Then, you can do something like this
for (int r = 7; r > -1; r--) {
for(int c = 65; c < 73; c++) {
name = Character.toString((char) c);
//or
name = "" + (char) c;
}
}

Java StringBuilder does not append strings

I am using StringBuilder in my project. When I appen char everything is OK, but when I try to append string "8 (" or ") " or " ", it stays empty "".
Example (EDITED):
int length = number.length();
CharSequence sequence = number.subSequence(0,length);
StringBuilder stringBuilder = new StringBuilder(17);
for (int i = 0; i < length; i++){
if (Pattern.matches("^[\\d]$", String.valueOf(sequence.charAt(i)))){
stringBuilder.append(sequence.charAt(i));
}
}
sequence = stringBuilder.toString();
stringBuilder = new StringBuilder(17);
CharSequence s = "8 (";
if (sequence.charAt(0) == 8 || sequence.charAt(0) == 7 || sequence.length() == 0){
stringBuilder.append(s);
}
for (int i = 1; i < 11 && i < sequence.length(); i++){
stringBuilder.append(sequence.charAt(i));
if (i == 3){
stringBuilder.append(") ");
}
if (i == 6 || i == 8){
stringBuilder.append(' ');
}
}
number.clear();
number.clearSpans();
number.append(stringBuilder.toString());
The problem with your code is
if (sequence.charAt(0) == 8 || sequence.charAt(0) == 7 ||
you need to compare to chars not ints
if (sequence.charAt(0) == '8' || etc

Using a for loop to search an array

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. :)

Creating an integer array based on a string in Java

for my compsci assignment we're supposed to take a string given to us with integers and letters in it, then create a method that takes that string and converts it into an integer array with the integers in it. For some reason my method is not adding ints to the array, I'm not sure why.
For the LETTERS given in the string, we're supposed to discard them, so we have an array with ONLY int values; ex. input: abs3131afas312 the array would have {3131,312}
This is the link to the assignment.
Here's my method:
public static int[] intParse(String a){
int[] array1 = new int[a.length()];
int b = 0;
for(int i = 0; i < a.length(); ++i)
{
int g = a.charAt(i);
if(g == 1 || g == 2 || g == 3 || g == 4 || g == 5 || g == 6 || g == 7 || g == 8 || g == 9 || g == 0)
{
String c;
for(int j = i; j < a.length(); ++j)
{
int k = a.charAt(j);
if(k != 1 && k != 2 && k != 3 && k != 4 && k != 5 && k != 6 && k != 7 && k != 8 && k != 9 && k != 0)
{
c = a.substring(j,k-1);
array1[b] += Integer.parseInt(c);
b++;
j = (a.length());
i = a.charAt(j);
}
else
{
c = a.substring(j,a.length());
array1[b] = Integer.parseInt(c);
j = a.length();
}
}
}
}
return array1;
}
Rather than comparing your characters to integers and using Integer.parseInt, you should be using the following very useful utility methods:
Character.isDigit(int codepoint)
Character.getNumericValue(int codepoint)
Also, your logic seems a little sketchy. When k is a digit code point, you are trying to parse the entire rest of the string. That doesn't seem consistent with what you're trying to do with the outer loop.
First of all, a is a string, and contains ASCII characters not integers. Character '1' is not equal to the integer 1. It is equal to the ASCII value of '1' which happens to be 49.
So first thing you should do is change that long if condition to:
char c = a.charAt(i);
if (c >= '0' && c <='9')
{
...
}
What you should do then is keep a string (a new string each time you encounter a non-numeric character and then a numeric character, and keep appending c to it until the character you find is non-numeric.
Then you can simply do Integer.parseInt(yourString) to get the number in an integer.
a fix for you:
char g = a.charAt(i);
if(g == '1' || g == '2' || g == '3' || g == '4' || g == '5' || g == '6' || g == '7' || g == '8' || g == '9' || g == '0') {
or much nicer:
char g = a.charAt(i);
if(g >= '0' && g <= '9') {
Your other if needs to be fixed, too
char k = a.charAt(j);
if(k < '0' || k > '9') {
You might prefer this approach:
Scanner sc = new Scanner("abs3131afas312");
String match;
while ((match = sc.findInLine("(\\d+)"))!=null) {
// instead of printing it, put it in your array
// or a list (and then convert to array)
System.out.println(Integer.parseInt(match));
}
sc.close();
Output:
3131
312

Categories