multiply chars by numbers in string - java

I would like multiply letter by number in a String and return other String.
I don't know how to concat it when number is higher than 9 and then multiply
eg.
String ="a2b10" convert to String ="aabbbbbbbbbb"
string can have different values: "a2b15", "a16b4c1","a11b14c5"
below I made it only for one letter and one number eg. a1b8, a4b7v3
import javafx.util.converter.CharacterStringConverter;
public class Test {
public static void main(String[] args) {
String txt = "a3b2";
char ch;
for (int i = 0; i < txt.length(); i++) {
ch = txt.charAt(i);
if (((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) {
} else if (ch >= '0' && ch <= '9')
{
int count = Character.getNumericValue(ch);
for (int j = 0; j < count; j++) {
System.out.print(txt.charAt(i - 1));
}
} else
System.out.println("not a letter");
}
}
}

In this case it's easier to use regex and group-matching to extract the letter and the number that's following it:
public static void main(String[] args) {
String txt = "a3b10";
String patt = "([a-z])([0-9]*)"; // ([a-z]) will be the first group and ([0-9]*) will be the second
Pattern pattern = Pattern.compile(patt);
Matcher matcher = pattern.matcher(txt);
while(matcher.find()) {
String letter = matcher.group(1);
String number = matcher.group(2);
int num = Integer.valueOf(number);
while (num > 0) {
System.out.print(letter);
num--;
}
}
}
OUTPUT
aaabbbbbbbbbb

You can do it like this ...
public class Test {
public static void main(String[] args) {
String txt = "a10b10";
char ch;
char tempChar = ' ';
int temp = -1;
for (int i = 0; i < txt.length(); i++) {
ch = txt.charAt(i);
if (((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))) {
temp = -1;
tempChar = ch;
} else if (ch >= '0' && ch <= '9') {
int count = Character.getNumericValue(ch);
if (temp != -1) {
count = ((10*temp) - temp);
}
for (int j = 0; j < count; j++) {
//System.out.print(txt.charAt(i - 1));
System.out.print(tempChar);
}
temp = count;
} else {
System.out.println("not a letter");
}
}
}
}

When you're looking for numbers and you find one, keep looking for numbers until you find a letter or the end of the string.

Related

How to convert from base 10 to base x in java?

What i've done so far:
public static String convert(int base, int target , String number) {
ArrayList<Integer> numbers= new ArrayList<Integer>();
for(int i=0;i<number.length();i++) {
char check=number.charAt(i);
if(check>='A') {
numbers.add(Character.getNumericValue(check-'A'+1));
}
else {
numbers.add(Character.getNumericValue(check));
}
}
int answer_10 = 0;
for(int i=0;i<number.length();i++) {
answer_10 += Math.pow(numbers.get(number.length()-i-1), base);
}
String answer_target ="";
while(answer_10>0) { // I need help on this part
for(int i=0;i>0;i++) {
if(9*Math.pow(target, i)-answer_10<0) {
i++;
}
else {
for(int j=9;j<=0;j--) {
if(j*Math.pow(target, i)-answer_10<0) {
j-=1;
if(j<=10) {
answer_target += j*Math.pow(target, i);
}
else {
answer_target += j-'A'+1 ;
}
answer_10 -= j*Math.pow(target, i);
break;
}
}
}
}
}
return answer_target;
}
I need help on the part that converts the number from base 10 to base x as a string.
The question limits 2<=x<=20.
I couldn't use the built-in converting function by java, as the question asked not to.
Math.pow isn't a good choice for this problem. It is better to use simple multiply /divide cycle.
public static String convert(int base, int target, String number) {
if (base < 2 || base > 20)
throw new IllegalArgumentException("Invalid base "+base);
if (target < 2 || target > 20)
throw new IllegalArgumentException("Invalid base "+target);
int numberStrLen = number.length();
int numberValue = 0;
for (int i = 0; i < numberStrLen; i++) {
char ch = Character.toLowerCase(number.charAt(i));
int digit;
if (ch >= '0' && ch <= '9')
digit = ch - '0';
else if (ch >= 'a')
digit = ch - 'a' + 10;
else
throw new IllegalArgumentException("Invalid character "+ch+" for base "+base);
if (digit >= base)
throw new IllegalArgumentException("Invalid character "+ch+" for base "+base);
numberValue = numberValue * base + digit; // <= multiply cycle
}
if (numberValue < 0)
throw new IllegalArgumentException("Signed value: "+numberValue+" for "+number);
StringBuilder sb = new StringBuilder();
while (numberValue != 0) {
int digit = numberValue % target;
numberValue = numberValue / target; // <= divide cycle
char ch;
if (digit < 10)
ch = (char)(digit + '0');
else
ch = (char)(digit - 10 + 'a');
sb.insert(0, ch);
}
if (sb.length() == 0)
return "0";
else
return sb.toString();
}
And don't forget about int overflow (wraparound ). Maybe use long or even BigInteger?

I need to print 1st and every 5th character from a given String in java

I have a String of a length of more than 1000 character. In this string i have to print 1st character after that every 5th character.
I tried writing a program to iterate from 0th character to last character and have a count variable.
If count is equal to 5. I am printing the character and count is initializing with 0.
private static String getMaskedToken(String token) {
if (token == null)
return null;
char[] charArray = token.toCharArray();
int length = token.length();
StringBuilder sb = new StringBuilder();
int count = 0;
for (int i = 0; i < length; i++) {
count++;
if (i == 0 || i == length - 1) {
sb.append(charArray[i]);
} else if (count == 5) {
sb.append(charArray[i]);
count=0;
} else if(count < 5 && i == length-1){
sb.append(charArray[i]);
}else {
sb.append('*');
}
}
return sb.toString();
}
Need to print last character if count is less than 5 of last
iteration.
If String of length 9, "12345678" then actual output will be like
1***5**8
If String of length 9, "123456789abcd" then actual output will be
like 1***5****a**d
String output = "";
for (int i = 0; i < str.length(); i++) {
if (i == 0) {
output += str.charAt(i);
output += "***";
output += str.charAt(4);
i = 4;
} else if ((i - 4) % 5 == 0) {
output += str.charAt(i);
} else if (i == str.length()-1) {
output += str.charAt(i);
} else {
output += "*";
}
}
System.out.println(output);
}
This will print 1***5****a**d for string "123456789abcd".
try this code:
public void printFirstAndEveryFifthCharecter(String str)
{
for (int i = 0 ; i < str.length() ; i++)
{
if ((i+1) == 1 | (i+1) % 5 == 0) {
System.out.print(str.charAt(i) + "***");
}
}
if (str.length() % 5 > 0) {
System.out.print(str.charAt(str.length() - 1));
}
}
Your code should work fine. Here's an alternative without using StringBuilder and with fewer checks.
private static String getFirstFifthLast(String str) {
String[] strArray = str.split(""); //returns an array of strings with length 1
int arrayLength = strArray.length;
String result = strArray[0]; //append the first element
//append element if it is in 5th position, append "*" otherwise
for (int i = 0; i < arrayLength; i++) {
if ((i + 1) % 5 == 0) {
result += strArray[i];
} else {
result += "*";
}
}
result += strArray[arrayLength - 1]; //append the last element
return result;
}
Try this code,
private void printEvery5thCharacter(String str) {
for (int i = 1; i < str.length() - 1; i += 5) {
System.out.print(str.charAt(i - 1) + "***");
if (i == 1) {
i = 0;
}
}
if (str.length() % 5 > 0) {
System.out.print(str.charAt(str.length() - 1));
}
}

Having a runtime error of ArrayIndexOutOfBoundsException: 97

I am having an error, can someone please help me out. I am trying to print highest occurring vowel in the string.
void vowelCount() {
int countO = 0 ,countU = 0,countI = 0 ,countA = 0 ,countE = 0 ;
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
int[] count = new int[] {countA,countE,countI,countO ,countU};
int maxCount = 0;
char maximumChar = ' ';
for (int i = 0; i < TEXT.length(); i++) {
char ch = TEXT.charAt(i);
if (ch == vowels[0]) {
countA++;
}
if (ch == vowels[1]) {
countE++;
}
if (ch == vowels[2]) {
countI++;
}
if (ch == vowels[3]) {
countO++;
}
if (ch == vowels[4]) {
countU++;
}
}
for( int i = 0; i< vowels.length ; i++) {
if (count[vowels[i]] > maxCount) {
maxCount = count[vowels[i]];
maximumChar = vowels[i];
}
}
System.out.println();
System.out.println("The most used lowercase vowel is " + maximumChar + " for " + maxCount + " times.");
}
Arrayindexoutofbound exception results, i am not quite sure where could me my error. Tried for such a long time still the error repeats.
I'd say that count[vowels[i]] is your problem. vowels[i] will not be in the range [0..4] and hence you exceed the bounds of your array. You want count[i] instead. You could try the following simplified code
void vowelCount() {
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
int[] count = new int[vowels.length];
int maxCount = 0;
char maximumChar = ' ';
for (int i = 0; i < TEXT.length(); i++) {
char ch = TEXT.charAt(i);
for (int j=0; j<vowels.length; j++) {
if (ch == vowels[j]) {
count[j]++;
break;
}
}
}
for (int i = 0; i<vowels.length; i++) {
if (count[i] > maxCount) {
maxCount = count[i];
maximumChar = vowels[i];
}
}
System.out.println();
System.out.println("The most used lowercase vowel is " + maximumChar + " for " + maxCount + " times.");
}
The problem is here - if (count[vowels[i]] > maxCount) {
vowels[i] will give you a vowel that is a char. When used as index to fetch from char array, the character gets converted into its ASCII value, which wont be in the range of 0 to 4.
I would say, you should try to find your mistakes, rather than finding a solution. Your following code doesn't do what you expect.
for (int i = 0; i < TEXT.length(); i++) {
char ch = TEXT.charAt(i);
if (ch == vowels[0]) {
countA++;
}
if (ch == vowels[1]) {
countE++;
}
if (ch == vowels[2]) {
countI++;
}
if (ch == vowels[3]) {
countO++;
}
if (ch == vowels[4]) {
countU++;
}
}
When you are updating the variables with countX++, it isn't modifying the values stored in the count[] array, because you already initialised them with 0s i.e. the initial values of countX.
You would get an ArrayIndexOutOfBoundsException, because of these lines:
if (count[vowels[i]] > maxCount) {
maxCount = count[vowels[i]];
maximumChar = vowels[i];
}
Here the vowels[i] is having chars, when you use it as count[vowels[i]] you are using the ascii value of the char stored in the vowels array as an index to access the value in the count array.
In the exception 97 is printed as it is the ascii value of the char 'a'.
You should increment the count array data instead of the variables countO, countU, etc.. variables. You also need to iterate through the count array and find the max number from it and also assign the character from the vowel array to the maximumChar variable.
static String TEXT = "teeaaaiist";
static void vowelCount() {
int countO = 0 ,countU = 0,countI = 0 ,countA = 0 ,countE = 0 ;
char[] vowels = { 'a', 'e', 'i', 'o', 'u' };
int[] count = new int[] {countA,countE,countI,countO ,countU};
int maxCount = 0;
char maximumChar = ' ';
for (int i = 0; i < TEXT.length(); i++) {
char ch = TEXT.charAt(i);
if (ch == vowels[0]) {
count[0]++;
}
if (ch == vowels[1]) {
count[1]++;
}
if (ch == vowels[2]) {
count[2]++;
}
if (ch == vowels[3]) {
count[3]++;
}
if (ch == vowels[4]) {
count[4]++;
}
}
for( int i = 0; i< count.length ; i++) {
if (count[i] > maxCount) {
maxCount = count[i];
maximumChar = vowels[i];
}
}
System.out.println();
System.out.println("The most used lowercase vowel is " + maximumChar + " for " + maxCount + " times.");
}
public static void main(String[] args) {
vowelCount();
}

Don't know how manipulate strings

Take as input S, a string. Write a function that replaces every odd character with the character having just higher ASCII code and every even character with the character having just lower ASCII code. Print the value returned.
package assignments;
import java.util.Scanner;
public class strings_odd_even_char {
static Scanner scn = new Scanner(System.in);
public static void main(String[] args) {
String str = scn.nextLine();
for (int i = 0; i < str.length(); i = i + 2) {
char ch = str.charAt(i);
ch = (char)((ch + 1));
System.out.println(ch);
}
for (int j = 1; j < str.length(); j = j + 2) {
char ch = str.charAt(j);
ch = (char)((ch - 1));
System.out.print(ch);
}
}
}
The problem with my code is that it is first printing the values for all the odd characters and then for even characters but what I want is that they get printed in proper sequence like for input --> abcg , the output should be --> badf .
I'd hold the "incremenet" value in a variable and alternate it between +1 and -1 as I go voer the characters:
private static String change(String s) {
StringBuilder sb = new StringBuilder(s.length());
int increment = 1;
for (int i = 0; i < s.length(); ++i) {
sb.append((char)(s.charAt(i) + increment));
increment *= -1;
}
return sb.toString();
}
Just use one loop that handles both characters:
for (int i = 0; i < str.length(); i = i + 2) {
char ch = str.charAt(i);
ch = (char) (ch + 1);
System.out.print(ch);
if (i + 1 < str.length()) {
ch = str.charAt(i + 1);
ch = (char) (ch - 1);
System.out.print(ch);
}
}
You only need to iterate one time but do different operation (char+1) or (char-1) depending on the i:
public static void main(String[] args) {
String str = scn.nextLine();
for(int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(i % 2 == 0) { // even
ch += 1;
} else { // odd
ch -= 1;
}
System.out.print(ch);
}
}
You are using two loops, but you only need one. You can use the % operator to tell if i is even or odd, and then either subtract or add accordingly:
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(i % 2 == 0) {
ch = (char)((ch + 1));
System.out.println(ch);
} else {
ch = (char)((ch - 1));
System.out.print(ch);
}
}
You can do it in one for loop, to do that you will need to check whether the current index is even or odd. if current index is even you will increment char and print, if it is odd you will decrement char and print. to check if even or odd using % operator
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if(i%2 == 0) {
ch = ch + 1;
System.out.println(ch);
continue;
}
ch = ch - 1;
System.out.println(ch);
}

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:*

Categories