Convert char A-Z to corresponding int. - java

i am trying to convert A char from an array (2nd and 3rd) slot to int value that correspond to eg. A = 1 , B= 2, etc. For A-Z.
I am thinking that the long way will be doing if(x.charAt(i) == 'a'){ int z = 1; } for the whole A - Z which i think it is a very practical method. Is there any method that can do the same thing with a shorter code?
public static void computeCheckDigit(String x){
char [] arr = new char[x.length()];
for(int i=0; i<x.length();i++){
arr[i] = x.charAt(i);
}
}

Try this:
arr[i] = Character.toLowerCase(x.charAt(i)) - 'a' + 1;
You have to use int Array instead char Array.
public static void main(String[] args) {
String x = "AbC";
int[] arr = new int[x.length()];
for (int i = 0; i < x.length(); i++) {
arr[i] = Character.toLowerCase(x.charAt(i)) - 'a' + 1;
}
System.out.println(Arrays.toString(arr));
}
Output:
[1, 2, 3]

Since you seem to be case agnostic, you might want to uppercase or lowercase the string first, but you'd want to be locale-aware:
// If you don't state a locale, and you are in Turkey,
// weird things can happen. Turkish has the İ character.
// Using lower case instead could lead to the ı character instead.
final String xu = x.toUpperCase(Locale.US);
for (int i = 0; i < xu.length(); ++i) {
arr[i] = xu.charAt(i) - 'A' + 1;
}
An alternative loop would use:
// Casing not necessary.
for (int i = 0; i < x.length(); ++i) {
// One character
String letter = x.substr(i, i+1);
// A is 10 in base 11 and higher. Z is 35 in base 36.
// Subtract 9 to have A-Z be 1-26.
arr[i] = Integer.valueOf(letter, 36) - 9;
}

Related

(Java Code) Return maximum occurring character in an input string

Can anyone please explain the process of this for loop which comes first in the code. If you print these two lines in the console, you get output [0 0 0 1 2]. I don't know "how it works behind the scene to increment the character count every time".
for (int i=0; i<len; i++)
count[str.charAt(i)]++;
//Code
public class GFG
{
static final int ASCII_SIZE = 256;
static char getMaxOccuringChar(String str)
{
// Create array to keep the count of individual
// characters and initialize the array as 0
int count[] = new int[ASCII_SIZE];
// Construct character count array from the input
// string.
int len = str.length();
for (int i=0; i<len; i++) //bit confused lines
count[str.charAt(i)]++;
int max = -1; // Initialize max count
char result = ' '; // Initialize result
// Traversing through the string and maintaining
// the count of each character
for (int i = 0; i < len; i++) {
if (max < count[str.charAt(i)]) {
max = count[str.charAt(i)];
result = str.charAt(i);
}
}
return result;
}
// Driver Method
public static void main(String[] args)
{
String str = "abcaa";
System.out.println("Max occurring character is " +
getMaxOccuringChar(str));
}
}
The for loop iterates over the string, the value of str.charAt(i) is the character of str at the index i.
Since every char corresponds to an int value (see more about that here) count[str.charAt(i)]++; increases the value of the count array at the index of the given char's corresponding int (see the ascii table to see which one that is).
So after the for loop count contains the number of occurences of every ascii character in str.
str.charAt(i) return char from str at the i position. Char can be used as index in array for example myarray['c'] because 'c' can be represented as number (see ASCII table).
So basically
for(int i=0; i<len; i++)
count[str.charAt(i)]++;
is counting how many times the same letter appears in string.
so for input string "aabc"
count['a'] = 2
count['b'] = 1
count['c'] = 1
Maximum occurring character in a single input string
public static char getMaxOccuringChar(String str) {
char result = ' ';
int len = str.length();
HashMap<Character, Integer> StrArray = new HashMap<Character, Integer>();
int val = 1;
for(int i =0; i<len; i++) {
char temp = str.charAt(i);
if(!StrArray.containsKey(temp)) {
StrArray.put(temp, val);
}else {
StrArray.put(temp, StrArray.get(temp)+1);
}
}
int MaxVal = 0;
for(char i : StrArray.keySet()) {
if(StrArray.get(i) > MaxVal) {
result = i;
MaxVal = StrArray.get(i);
}
}
return result;
}

Putting all 8-bit binary sequences into a string array Java

what I am trying to put all possible 256 binary bit sequences into a string array. In order to do that, I have created 8 for loops to have all the possible cases. Here's what I've tried so far.
static String[] BitSequences() {
int[] result = new int[256];
for (int a = 0; a < 256; a++) {
for (int i = 0; i < 2; i++){
for (int j = 0; j < 2; j++){
for (int k = 0; k < 2; k++){
for (int l = 0; l < 2; l++){
for (int m = 0; m < 2; m++){
for (int n = 0; n < 2; n++){
for (int o = 0; o < 2; o++){
for (int p = 0; p < 2; p++){
result[a] = ; //this part is a problem
}
}
}
}
}
}
}
}
}
String str = Arrays.toString(result);
System.out.println(str);
return str;
}
This method is supposed to return a string array that contains all the possible cases. However, I don't know how to insert these value by making for-loops using int values. It is easy to print it out:
'
System.out.println(i+j+k+.....+p)
'
any help would be appreciated!
Consider using the built in conversion method for binary strings:
static String[] BitSequences() {
String[] result = new String[256];
for (int a = 0; a < 256; a++) {
result[a] = Integer.toBinaryString(a);
}
String str = Arrays.toString(result);
System.out.println(str);
return str;
}
An 8-bit, two's complement integer ranges from -128 to 127. To represent that range, we can use IntStream#rangeClosed.
From this answer, we can utilize BigInteger to left-pad the binary String (generated by Integer#toBinaryString) with 0s if its length is less than 8 (denoting that the value is positive).
Otherwise, the value represents a negative number, and its respective binary string will have a length greater than 8, which must be truncated to 8 characters using String#substring.
Finally, the Stream<String> can be collected to a String[] using Stream#toArray.
public static String[] generateBitSequences() {
return IntStream.rangeClosed(-128, 127)
.mapToObj(Integer::toBinaryString)
.map(BigInteger::new)
.map(b -> String.format("%08d", b)) // Left pad positive values with 0s.
.map(s -> s.substring(s.length() - 8)) // Remove leading 1s from negative values.
.toArray(String[]::new);
}
Output:
[10000000, 10000001, ..., 01111110, 01111111]

There is string "naveen" , want output as "eennav"

I have string in java "naveen" i want output as "eennav". Please help me out in this. The idea is that the characters are to be ordered in order of frequency, and, where frequencies are the same, alphabetically.
Thanks
I have tried to find duplicates in the string , but am not able to get the required output .
String str="naveen";
int count =0;
char[] charr=str.toCharArray();
for(int i=0;i<charr.length;i++) {
//System.out.println(s[i]);
for(int j=i+1;j<charr.length;j++) {
if(charr[i]==(charr[j])) {
System.out.println(charr[i]);
}
Assuming the question is asking us to take a string containing only lower case letters and organize them by frequency of letters (high to low) and within that by alphabetical order, we can do it as below.
The strategy is first to make a pass through the characters of the input string and count the number of occurrences of each. Then we look through the counts for letters and find the largest. Working from the largest down to 1, we run through the alphabet for characters that occur that many times, and append that many of them to the result string.
There is a little bit of work involved here to convert back and forth from 'a' to 0 and 0 to 'a' and so on to 25 and 'z'.
This approach could be extended, but since the question didn't specify, I chose to make simplifying assumptions. I also did not work on optimizing, just getting it to work.
public class MyClass {
public static void main(String args[]) {
String str = "naveen"; //this string may change, but it is assumed to be all lower case letters by this implementation
int[] counts = new int[26]; //frequency count of letters a to z
for (int i = 0; i < 26; i++) {
counts[i] = 0; // intially 0 of any letter
}
char[] charr = str.toCharArray();
for (int i = 0; i < charr.length; i++) {
counts[(int)(charr[i]) - (int)('a')]++; // increment corresponding spot in counts array, spot 0 for 'a' through 25 for 'z'
}
int maxCount = counts[0]; // now find the most occurrences of any letter
for (int i = 1; i < counts.length; i++) {
if (counts[i] > maxCount) {
maxCount = counts[i];
}
}
String result = ""; // string to return
for (int j = maxCount; j > 0; j--) { // work down from most frequently occuring, within that alphabetically
for (int i = 0; i < 26; i++) {
if (counts[i] == j) {
//System.out.println("there are "+j+" of the letter "+(char)((int)('a'+i)));
for (int k = 0; k < j; k++) {
result = result + (char)((int)('a' + i));
}
};
}
}
System.out.println(result);
}
}

Multiply the number based on its length

I wanted to multiply the number based on its String length.
For example
String s = "153";
So, here the length of the above string is 3. So i wanted to multiply each number in the string 3 times (which is the actual length of the string)
Something like below
Here the length is 3
Something like this 1*1*1+5*5*5+3*3*3
Can anyone please help me in that?
This is what I have tried:
int number = 153;
String originalNumber = number+"";
char[] ch = originalNumber.toCharArray();
int length = originalNumber.length();
for (int i = 0; i < ch.length; i++) {
char c = ch[i];
for (int j = 0; j < ch.length; j++) {
// I'm stuck here
}
}
So you have to take each digit and take it to the power of the length of your string, then add all those results up.
You could do the following:
String s = "153";
int result = 0;
for (char n : s.toCharArray())
if (Character.isDigit(n))
result += Math.pow(Character.getNumericValue(n), s.length());
System.out.println(result);
It prints:
153
I added a safety check to see if the char is actually a digit (if (Character.isDigit(n))).
Classic solution : You need to turn each char, in an int then use use power to the length and sum all :
int res = 0;
for (int i = 0; i < ch.length; i++) {
int newNb = (int) Math.pow(Character.digit(ch[i], 10), ch.length);
res += newNb;
}
for-each loop solution
for (char c : ch) {
int newNb = (int) Math.pow(c - '0', ch.length);
res += newNb;
}
To turn a char c to its corresponding int value you can do :
int a = Character.getNumericValue(c);
int a = Character.digit(c, 10);
int a = c - '0';
You could simply iterate over each digit of the given string and calculate it's power. It is better to use str.charAt(i) instead of str.toCharArray() to not create additional char[].
public static int multiplyNumberLength(String str) {
int res = 0;
for (int i = 0; i < str.length(); i++)
if (Character.isDigit(str.charAt(i)))
res += Math.pow(str.charAt(i) - '0', str.length());
return res;
}
To turn a character back into a digit:
char c = ch[i];
int digit = c - '0';
int product = 1;
then for your inner loop multiply the digit into the product.

Java Create Strings Dynamically With Loops

I need to create a program that creates strings dynamically with some sort of loop (for/while). It would start out as a single-character string with an ASCII value of 1, than 2, than 3, and so on, until is reached 128. Once it reached 128, it would be a two-character string, with the first character of an ASCII value of 1, and the second character being 1. It would then be 1;1, 1;2, 1;3, until the second digit reached 128, and then which the first character would have a value of 2. How is this logically possible?
Here's what I tried so far:
for (int i = 0; i < 128; i++) {
str = ((char) i) + "";
for (int j = 0; j < 128; j++) {
str += ((char) j) + "";
//workWithString(str);
System.out.println(str);
str = str.substring(0, str.length() - 1);
}
}
And this works, but only for 2 digits. I would like for it to work with up to 32 digits. Is there any easier way to accomplish this without having 32 for loops?
Thanks!
Sorry, guys. Figured it out on my own. For anyone who's interested in the answer, I achieved it like so:
public static void addCharacter(String str, int depth) {
for (int j = 33; j < 127; j++) {
for (int i = 0; i < depth; i++) {
str += ((char) j) + "";
System.out.println(str);
addCharacter(str, depth - 1);
str = str.substring(0, str.length() - 1);
}
}
}
Where depth is the amount of digits you want it to calculate, and str is the string you want to add a character to.
public class StringCreator {
public static void main(String[] args) {
for(int i=0;i<=128;i++){
for(j=0;j<10;j++){
System.out.println(i+"."+j);
}
}
}
}

Categories

Resources