This question already has answers here:
How to map character to numeric position in java?
(7 answers)
Closed 5 years ago.
How to get numeric position of alphabets in java ?
Suppose through command prompt i have entered abc then as a output i need to get 123 how can i get the numeric position of alphabets in java?
Thanks in advance.
String str = "abcdef";
char[] ch = str.toCharArray();
for(char c : ch){
int temp = (int)c;
int temp_integer = 96; //for lower case
if(temp<=122 & temp>=97)
System.out.print(temp-temp_integer);
}
Output:
123456
#Shiki for Capital/UpperCase letters use the following code:
String str = "DEFGHI";
char[] ch = str.toCharArray();
for(char c : ch){
int temp = (int)c;
int temp_integer = 64; //for upper case
if(temp<=90 & temp>=65)
System.out.print(temp-temp_integer);
}
Output:
456789
Another way to do this problem besides using ASCII conversions is the following:
String input = "abc".toLowerCase();
final static String alphabet = "abcdefghijklmnopqrstuvwxyz";
for(int i=0; i < input.length(); i++){
System.out.print(alphabet.indexOf(input.charAt(i))+1);
}
Convert each character to its ASCII code, subtract the ASCII code for "a" and add 1. I'm deliberately leaving the code as an exercise.
This sounds like homework. If so, please tag it as such.
Also, this won't deal with upper case letters, since you didn't state any requirement to handle them, but if you need to then just lowercase the string before you start.
Oh, and this will only deal with the latin "a" through "z" characters without any accents, etc.
char letter;
for(int i=0; i<text.length(); i++)
{
letter = text.charAt(i);
if(letter>='A' && letter<='Z')
System.out.println((int)letter - 'A'+1);
if(letter>='a' && letter<= 'z')
System.out.println((int)letter - 'a'+1);
}
This depends on the alphabet but for the english one, try this:
String input = "abc".toLowerCase(); //note the to lower case in order to treat a and A the same way
for( int i = 0; i < input.length(); ++i) {
int position = input.charAt(i) - 'a' + 1;
}
First you need to write a loop to iterate over the characters in the string. Take a look at the String class which has methods to give you its length and to find the charAt at each index.
For each character, you need to work out its numeric position. Take a look at this question to see how this could be done.
just logic I can suggest take two arrays.
one is Char array
and another is int array.
convert ur input string to char array,get the position of char from char and int array.
dont expect source code here
String word = "blah blah";
for(int i =0;i<word.length;++i)
{
if(Character.isLowerCase(word.charAt(i)){
System.out.print((int)word.charAt(i) - (int)'a'+1);
}
else{
System.out.print((int)word.charAt(i)-(int)'A' +1);
}
}
Related
Given a string, I have to replace all vowels with their respective position in the array. However, my code returns some strange symbols instead of numbers. Where's the problem?
String s = "this is my string";
char p = 1;
char[] formatted = s.toCharArray();
for(int i = 0; i < formatted.length; i++) {
if(formatted[i] == 'a' ||formatted[i] == 'e' ||formatted[i] == 'i'
||formatted[i] == 'o' ||formatted[i] == 'u') {
formatted[i] = p;
}
p++;
}
s = String.valueOf(formatted);
System.out.println(s);
P.S: Numbers are bigger than 10
this is my s t r i n g
012345678910 11 12 13 14
The position of i in string is 14 but 14 is not a character; it's a numeric string. It means that you need to deal with strings instead of characters. Split s using "" as the delimiter, process the resulting array and finally join the array back into a string using "" as the delimiter.
class Main {
public static void main(String[] args) {
String s = "this is my string";
String[] formatted = s.split("");
for (int i = 0; i < formatted.length; i++) {
if (formatted[i].matches("(?i)[aeiou]")) {
formatted[i] = String.valueOf(i);
}
}
s = String.join("", formatted);
System.out.println(s);
}
}
Output:
th2s 5s my str14ng
The regex, (?i)[aeiou] specifies case-insensitive match for one of the vowels where (?i) specifies the case-insensitiveness. Test it here.
The character '1' has a different value from the number 1.
You can change
char p = 1;
to
char p = '1';
and I think that will give you what you want, as long you're not trying to insert more than 9 numbers in your string. Otherwise you'll need to cope with inserting extra digits, which you cannot do into a char-array, because it has a fixed length.
the root of the problem is already in the comments,
in java the types make a difference in memory size and its representation
int x = 1;
and
char y = '1'
are not holding the same value, this is because many numerical representations are related with ascii codes and the value you have to assing to y to get the number 1 printed is HEX 0x31 or DEC 49.
take a look at the ascci table
I'm looking for a way to compare two strings to each other character by character.
It should show whether there are other characters which don't appear in both strings.
Does someone have a solution for?
for(int j=0; j < min; j++) {
s1 = w1.substring(j,j+1);
s2 = w2.substring(j,j+1);
if (!s1.equalsIgnoreCase(s2) ){
counter++;
}
}
This only looks sequential for differences. But I want to find out whether there are differences between those two strings at all.
So **abc** and **cab** should count as a hit
I think what you want is to show that 2 strings have the same letters and the same amount of each letter. Use 2 hashsets, where the key is the character and the value is the number of occurrence in the string. you'll have one hashset for each string, then loop through the string add the characters to the set and compare to see if the sets are equal.
Turn them into charArrays and add the differences to an empty string as a for loop scans through them, for instance
String a = "abc";
char[] aa = a.toCharArray();
String b = "cba";
char[] bb = b.toCharArray();
String dif;
public void differ() {
for(int i = 0; i < aa.length - 1; i++) {
if(!aa[i].equals(bb[i])) {
dif += aa[i];
}
}
}
I believe running differ() would return "ac" because they both have b in the middle. Is this what you wanted?
The instructions are to count how many digits are in every string of an array and assign to numberDigits.
What am I doing wrong here?
public void computeStatistics(String []strings){
numberDigits = 0;
for(String s : strings){
for(int i : s.toCharArray()){
if(i >= 0 || i <= 2)
numberDigits++;
}
}
}
Alternatively, since overall digits count matter, all strings can be concatenated to single and each character can be checked for if it is digit.
public void computeStatistics(String[] strings) {
numberDigits = 0;
//Converting all strings in array to single string
String cmbStr = Arrays.toString(strings);
for (Character c : cmbStr.toCharArray()) {
//checking each character is digit
if (Character.isDigit(c))
numberDigits++;
}
}
Not really sure if i understood your question correctly are you counting the number of digits in a string array?
public int computeStatistics(String []strings){
int numberDigits = 0;
for(String s : strings){
s = s.replaceAll("\D+","");
numberDigits = numberDigits + s.length();
}
return numberDigits;
}
I am assuming that your string is alpha nummeric. Your if condition is wrong. char datatype have integer representations of their corresponding ASCII value. So char a = 'A' when casted to int is actually stored as 65. So the char '0' which is stored in the array you are iterating over is stored in i as 48. You are checking between 0 to 9 ascii codes and hence this code wont work. Either change if condition to
if(i>=48 && i<=57)
Or what i find as a good general policy is to keep char as char.
for(char ch:s.toCharArrat())
if(ch>='0' && ch<='9')
This way you wont have to think about ascii. For converting char '0' to int do the following.
int i = (int)ch - (int)'0';
This will give corresponding integers.
I have the following code which changes lowercase letters to uppercase letters of the private instance array letters and returns a string.
public String toUpperCase()
{
char[] duplicate = new char [letters.length];
duplicate = letters;
String upperCase = "";
int a = 0;
int b = 0;
for (int i =0; i < duplicate.length; i++)
{
a = duplicate[i];
if (a >= 97 && a <= 122)
{
b = a - 32;
duplicate[i] = (char) b;
}
upperCase = upperCase + duplicate[i];
}
return upperCase;
}
the problem is the original contents of the array letters have been changed to uppercase after this method is called. I created a new array, duplicate, and set it equal to letters in hopes I can change the lowercase letters in the array letters to uppercase without changing the original array. However, this didn't work. How can I change the lowercase letters of the array letters to uppercase without changing the original array?
try this:
char[] duplicate = letters.clone();
that way the original array does not change
How can I change the lowercase letters of the array letters to uppercase without changing the original array?
Don't assign the letter array instance to the variable duplicate. Instead use System.arraycopy(letters, 0, duplicate, 0, letters.length) which copies the contents of letters to duplicate.
duplicate = letters; ... you are assigning the original value to the duplicates, these two arrays now point to the same location. So any modifications to duplicate will be mirrored by letters automatically (they both point to the same location in memory).
Instead, you need to use letters to obtain the original values and store the modifications within duplicate
public String toUpperCase() {
char[] duplicate = new char[letters.length];
String upperCase = "";
int a = 0;
int b = 0;
for (int i = 0; i < letters.length; i++) {
a = letters[i];
if (a >= 97 && a <= 122) {
b = a - 32;
duplicate[i] = (char) b;
}
upperCase = upperCase + duplicate[i];
}
return upperCase;
}
Unless you have some reason not to, you can also make use of the Character class to help you detect lower case characters and convert them to upper case, for example...
if (Character.isLowerCase(a)) {
letters[i] = Character.toUpperCase(a);
}
or you could just use letters[i] = Character.toUpperCase(a); as it won't double convert upper case characters
This all leads me to wonder why you need the duplicate array to begin with, in the end, you could just get away with something like...
public String toUpperCase() {
StringBuilder upperCase = new StringBuilder(letters.length);
for (char c : letters) {
upperCase.append(Character.toUpperCase(c));
}
return upperCase.toString();
}
or just
public String toUpperCase() {
return new String(letters).toUpperCase()
}
While other answers work too, you don't actually have to copy the array...
Just do,
if (a >= 97 && a <= 122)
{
b = a - 32;
upperCase = upperCase + (char) b;
}
else
upperCase = upperCase + duplicate[i];
This doesn't do what you think it does:
char[] duplicate = new char [letters.length];
duplicate = letters;
The first line allocates a new array. The second line does not fill the new array. Far from it. The second line points duplicate to letters. That is, duplicate and letters both point to the same data. Manipulating duplicate manipulates letters too.
To make duplicate a real duplicate, you need to copy the content. An easy way to do just that:
char[] duplicate = letters.clone();
Another way to copy the content:
char[] duplicate = new char [letters.length];
System.arraycopy(letters, 0, duplicate, 0, letters.length);
How to get alphabets by the numeric postion in java ?
Suppose i have entered 1 then as a output i need to get A how can i get the alphabets position in java?
Thanks in advance.
Try this
int i = 1;
System.out.println((char)(i+'A'-1));
int charValue = 1; //this is the number you enter
char letter = (char)(charValue+64); //this is the character you want
For lowercase letters, use (charValue+96)
You could use a switch/case statement to manually get each letter however a better solution would be to use the ASCII table to get the letters.
ASCII Table: http://www.ascii-code.com/
public char getLetter(int i)
{
return (char) (i + 64);
}
The above function would return 'A' when i is 1
You have letters/characters, think of them as positions in an array.
int number = 0;
String[] array = new String[] {"a", "b", "c", "..."};
String letter = array[number + 1];