String c="12345";
for(char k:c.toCharArray())
System.out.print(k+4);
This program outputs:
5354555657
I don't really understand why this is out putting those numbers. The only pattern I see is that it prints a "5" then takes the "1" from the string and adds 2 to make "3". Then prints a "5" then takes the "2" from the string and adds 2 to make "4" then prints a "5" and so on.
The characters in the array, when promoted to int for the addition of 4, take on their underlying Unicode value, of which the ASCII values are a subset. The digits 0-9 are represented by codes 48-57 respectively. Characters '1' through '5' are 49-53, then you add 4 and get 53-57.
After adding, cast the sum back to char so print can interpret it as a char.
System.out.print( (char) (k+4));
Output:
56789
This is because you're adding an int to a character (it's casting your character to an int and then adding it to 4, then printing it out).
You need to do:
System.out.println(Character.getNumericValue(k) + 4);
Related
I have a capital letter defined in a variable string, and I want to output the next and previous letters in the alphabet. For example, if the variable was equal to 'C', I would want to output 'B' and 'D'.
One way:
String value = "C";
int charValue = value.charAt(0);
String next = String.valueOf( (char) (charValue + 1));
System.out.println(next);
Well if you mean the 'ABC' then they split into two sequences a-z and A-Z, the simplest way I think would be to use a char variable and to increment the index by one.
char letter='c';
letter++; // (letter=='d')
same goes for decrement:
char letter='c';
letter--; // (letter=='b')
thing is that the representation of the letters a-z are 97-122 and A-Z are 65-90, so if the case of the letter is important you need to pay attention to it.
If you are limited to the latin alphabet, you can use the fact that the characters in the ASCII table are ordered alphabetically, so:
System.out.println((char) ('C' + 1));
System.out.println((char) ('C' - 1));
outputs D and B.
What you do is add a char and an int, thus effectively adding the int to the ascii code of the char. When you cast back to char, the ascii code is converted to a character.
All the answers are correct but none seem to give a full explanation so I'll try. Just like any other type, a char is stored as a number (16-bit in Java). Unlike other non-numeric types, the mapping of the values of the stored numbers to the values of the chars they represent are well known. This mapping is called the ASCII Table. The Java compiler treats chars as a 16-bit number and therefore you can do the following:
System.out.print((int)'A'); // prints 65
System.out.print((char)65); // prints A
For this reason, the ++, -- and other mathematical operations apply to chars and provide a way to increment\decrement their values.
Note that the casting is cyclic when you exceed 16-bit:
System.out.print((char)65601); // also prints A
System.out.print((char)-65471); // also prints A
P.S. This also applies to Kotlin:
println('A'.toInt()) // prints 65
println(65.toChar()) // prints A
println(65601.toChar()) // prints A
println((-65471).toChar()) // prints A
just like this :
System.out.printf("%c\n",letter);
letter++;
for the following code,
why there is empty string in position 2,3,5,6,8?
then why "b", ":andf", "1" has no empty string behind?
String[] splitStrs = "booo:and:fooo1o".split("o", -1);
System.out.println(splitStrs.length);
for (int i=0; i<splitStrs.length; i++) {
System.out.println("\"" + splitStrs[i]+ "\"");
}
output is:
8
"b"
""
""
":and:f"
""
""
"1"
""
why there is empty string in position 2,3,5,6,8?
When splitting on "o", there's nothing between the o's in "ooo", thus empty strings.
then why "b", ":andf", "1" has no empty string behind?
But there is an empty string at the end of your output, i.e., behind "1".
Per the documentation, a negative 2nd arg specifically means "trailing empty strings not discarded".
Always read the doc.
The split method will find all occurances where is wanted character (in your example "o"), put a new (sub)string between current "o" and next "o", without the "o" character, in array, and continue for the whole string.
When you have, for an example "oo", it will be "" since there is nothing between those 2 "o" characters.
Let's take an example. You have a string "Oh, hello Anna! I havent seen you since 2010s!" and split this string on every place where is "a" character.
First, start from the first character, then find where is next letter "a", which is found on 14th index. Take part of the string from start to that place where is "a" and add it into an array. First element of an array will look like "Oh, hello Ann" ("A" and "a" are different characters). Then start from that "a" where I have found (14th index) and find next "a" , which is in 20th index in our example. Take part of the string from first and second "a" and copy it in an array. Then the procedure goes on until the end of the string.
Result will be:
"Oh, hello Ann"
"! I h"
"vent seen you since 2010s!"
If we split our same string on every "n", by using same logic, we will get:
"Oh, hello A"
""
"a! I have"
"t see"
" you si"
"ce 2010s"
Reason why I get an empty string on second part is because in "...Anna...", there is nothing between those 2 "n" characters
Some examples can be found on: https://www.geeksforgeeks.org/split-string-java-examples/
Public String [ ] split ( String regex, int limit ) Parameters:
regex – a delimiting regular expression
Limit – the resulting
threshold
The limit parameter can have 3 values:
limit > 0 – If this is the case, then the pattern will be applied at
most limit-1 times, the resulting array’s length will not be more
than n, and the resulting array’s last entry will contain all input
beyond the last matched pattern.
limit < 0 – In this case, the
pattern will be applied as many times as possible, and the resulting
array can be of any size.
limit = 0 – In this case, the pattern will
be applied as many times as possible, the resulting array can be of
any size, and trailing empty strings will be discarded.
please visit GeeksforGeeks site for more information regarding spliting.
"booo:and:fooo1o".split("o", -1);
why there is empty string in position 2,3,5,6,8?
Since the limit is -1 we can split it any number of times. When 'o' is used as the regex it will give all the values which are before it since there is no value it returns empty string
then why "b", ":andf", "1" has no empty string behind?
There is no empty string because there are characters after the 'o' previous match.
See this example:
class Split{
public static void main(final String ... $){
var out = System.out;
final String s = "ooa";
for(final String str : s.split("o", -1))
out.println("\""+str+"\"");
}
}
Output:
$ javac Split.java && java Split
""
""
"a"
Why this output?
When first match happens # index 0 which is also the very first character and it returns string before it but since there is no string it returns an empty string.
Then when second match happens with o # index 1 it returns the string after the first match and before index 1. Since there is no characters it returns an empty string.
After that it returns a.
i would understand why the output is 3 and not a char ('5' unicode character)
char c='5';
c = (char) (c - 2);
System.out.println(c);
and could you please explain what's the difference beetween code ASCII and unicode character ?
thank you in advance :)
It is a character. It's a character representing the numeral 3, just as '3' is a character on your keyboard.
When you subtract one from a character, you get the character immediately before that. For example, 'B' - 1 = A.
You start with the character '5' and subtract two, giving the character '3'. If you subtracted 6, you would not get -1, you'd get a random character ('/' I think).
Basically this subtraction works because the characters 0 - 9 are stored contiguously.
The output is the char '3', not the number 3.
When you subtract 2 from the char '5' and cast the result to char, you get the char '3'.
The char type is a numeric primitive type. Each character has a corresponding integer value between 0 and 2^16-1. The integer value of the character '3' is smaller by 2 than the value of the character '5'.
I have a quick question relating to ASCII and encoding. I am looking to take the input from a user - for example: "cat" - and turn it into a code. The code is as follows:
All lower case letters are converted to capital letters.
The first letter in the encoded message is stored as it's ASCII code value.
All subsequent letters are represented as the offset between the current letter and the previous letter.
For example: "cat" = 67 -2 19 since "C" = 67, "A" is -2 letters away from "C", and "T" is 19 letters away from "A". Any help would be greatly appreciated!
Scanner input = new Scanner(System.in);
String s = input.next().toUpperCase();
int ascii = s.charAt(0);
System.out.println(ascii);
for (int i = 1; i < s.length(); i++) {
ascii = s.charAt(i - 1);
System.out.println(s.charAt(i) - ascii);
}
To convert to capital letters there is the toUpperCase() method which returns the string with all capital letters.
To get the ASCII code of a letter you can simply create an integer and assign it the desired character (in this case the first letter of the string, so int ascii = s.charAt(0);).
To get the offsets you can use a for-loop starting from 1 (the second letter) where you get the ASCII code of the previous character and subtract it from the current one.
I am using the toCharArray method to convert a string to an array of type char but every time i try to print the array, it is printing numbers instead of the characters stored in the string. When i print the string the characters are printed just fine.
char[] nArray = capitalizedSentence.toCharArray();
for (int i = 0; i < nArray.length; i++)
{
System.out.println(nArray[i] + '\n');
}
EXAMPLE:
If my capitalizedSentence string has the value "Saad", when i convert it to a character array and print it, it prints the following:
93
75
75
78
can someone please help me so that it prints the individual characters stored in the capitalizedSentence string?
nArray[i] is a char; so is the '\n' constant. Character is an unsigned integral type, so characters are added together in the same way as all integers - numerically. When an addition happens, you end up with an int, not a char, so calling println on it produces a numeric result.
Removing + '\n' will fix the problem. You would get a newline character from println, so all characters would appear on a new line.
Demo.
Replace '\n' with "\n"
Why? Because the compiler sees you adding 2 characters together, to the compiler char and int primitive data types are considered to interchangeable and so the + is actually adding the 2 int values together. Using double quotes will tell the compiler that you are adding a string to a character.
I think this will help you. Use for-each loop
char[] nArray = capitalizedSentence.toCharArray();
for(Character c: nArray ){
System.out.println(c);
}