Java character to String - java

I tried multiple versions, including several solutions found here on StackOverflow, but I always get numbers instead of the characters in the console. For a homework in my uni, we need to invert the characters in a string. But creating the new string seems to be not so easy.
I tried using a StringBuilder,
StringBuilder builder = new StringBuilder();
// ...
builder.append(c); // c of type char
String concatenation,
System.out.print("" + c); // c of type char
and even String.valueOf(),
System.out.print(String.valueOf(c)); // c of type char
and each of them again with explicit conversion to char. But I always get the ordinal number of the characters in a sequence instead of the actual characters as output in the console. How do I correctly build a new string from chars?
/**
* Praktikum Informatik - IN0002
* Arbeitsblatt 02 - Aufgabe 2.6 (Buchstaben invertieren)
*/
public class H0206 {
public static String readLine() {
final StringBuilder builder = new StringBuilder();
try {
// Read until a newline character was found.
while (true) {
int c = System.in.read();
if (c == '\n')
break;
builder.append(c);
}
}
catch (java.io.IOException e) {
; // We assume that the end of the stream was reached.
}
return builder.toString();
}
public static void main(String[] args) {
// Read the first line from the terminal.
final String input = readLine();
// Create a lowercase and uppercase version of the line.
final String lowercase = input.toLowerCase();
final String uppercase = input.toUpperCase();
// Convert the string on the fly and print it out.
for (int i=0; i < input.length(); ++i) {
// If the character is the same in the lowercase
// version, we'll use the uppercase version instead.
char c = input.charAt(i);
if (lowercase.charAt(i) == c)
c = uppercase.charAt(i);
System.out.print(Character.toString(c));
}
System.out.println();
}
}

The problem I see with the sample code you provided is here:
int c = System.in.read();
if (c == '\n')
break;
builder.append(c);
The way you call the method, Stringbuilder.append(int) will be called. As the javadoc says, "the overall effect is exactly as if the argument were converted to a string by the method String.valueOf(int), and the characters of that string were then appended to this character sequence". Casting the integer-value to char like this will result in the desired behavior:
int c = System.in.read();
if (c == '\n')
break;
builder.append((char) c);

Here is a sample how to invert a String, there is another options, i think this one is more didacticism
public static void main(final String[] args) {
String text = "This is a string that will be inverted";
char[] charArray = text.toCharArray();
char[] invertedCharArray = new char[charArray.length];
for (int i = 1; i <= charArray.length; i++) {
char c = charArray[charArray.length - i];
invertedCharArray[i - 1] = c;
}
System.out.println(text);
System.out.println(new String(invertedCharArray));
}

try { // Read until a newline character was found.
while (true) {
int c = System.in.read();
if (c == '\n') break;
builder.append(c);
}
From the sample you gave, I can see that this is causing the problem. Because you are reading the char input as an int, it converts the char to its ordinal value so it can be stored (and therefore used) as an integer.
In public final class StringBuilder you're calling append(int i), which returns int. If int c = System.out.read();
is required for this to be declared as an integer, you can cast c to a char.
char ch = (char)c;
builder.append(ch)
If needed, this leaves c as an integer and stores its "original value" (What it was before it was turned into an int, i.e. the key pressed) in a variable if needed. If you only need to add it to the string, without reusing it for any reason, you can cast c to a char directly with append((char) c).

Related

What is the best way to replace a letter with the letter following it in the alphabet in Java?

I'm a programming newbie and I am doing a coderbyte exercise that says "
Replace every letter in the string with the letter following it in the alphabet (ie. c becomes d, z becomes a)"
i'm thinking of the following methods:
declare a string called "abcdefghijklmnopqrstuvxyz" and compare each string's char index position with the alphabet's index position, and then just bring the alphabet char that is located at the i+1 index location. But I don't know how it would work from z to a.
I've seen some techniques using ASCII values for every char but I've never done that before and not sure how it works
convert the given string into a char[] array, but then I'm not sure how I would tell the system to get me the next alphabet char
What would be the easiest way to do this?
EDIT
this is my code so far, but it doesn't work.
import java.util.*;
import java.io.*;
class Main {
public static String LetterChanges(String str) {
// code goes here
String alphabet = "abcdefghijklmnopqrstuvwxyz";
String newWord = "";
for (int i = 0; i < str.length(); i++){
for (int j = 0; j < alphabet.length(); i++){
if (str[i] == alphabet[i]){
if (alphabet[i+1].isVowel()){
newWord = newWord + toUpperCase(alphabet[i+1]);
}
else{
newWord = newWord + alphabet[i+1];
}
}
}
}
return str;
}
public static void main (String[] args) {
// keep this function call here
Scanner s = new Scanner(System.in);
System.out.print(LetterChanges(s.nextLine()));
}
}
Can't I ask for the index position of a Char that is a part of a String? in C I could do that.
Other than that not sure why it doesn't work.
I would definitely go with method 1.
I believe what you're looking for is the indexOf method on a String.
First of, I would create a method that given a character finds the next letter in the alphabet and return that. This could be done by finding the letter in your alphabet string and then fetch the letter at index+1. As you also pointed out you would need to take care of the edge case to turn 'z' into 'a', could by done with an if-statement or by having an extra letter 'a' at the end of your alphabet string.
Now all that remains to do is create a loop that runs over all characters in the message and calls the previously made method on that character and constuct a new string with the output.
Hope this helps you figure out a solution.
Assuming that there would be only lower case English letters in the given String the most performant way would be to add +1 to every character, and use either if-statement checking whethe the initial character was z or use the modulo operator % as #sp00m has pointed out in the comment.
Performing a search in the alphabetic string (option 1 in your list) is redundant, as well extracting array char[] from the given string (option 3).
Checking the edge case:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = str.charAt(i);
if (next == 'z') result.append('a'); // checking the edge case
else result.append((char) (next + 1));
}
return result.toString();
}
Applying modulo operator:
public static String shiftLetters(String str) {
StringBuilder result = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
char next = (char) ((str.charAt(i) - 'a' + 1) % 26 + 'a');
result.append(next);
}
return result.toString();
}
main()
public static void main(String[] args) {
System.out.println(shiftLetters("abc"));
System.out.println(shiftLetters("wxyz"));
}
Output:
bcd // "abc"
xyza // "wxyz"

Error to find the first no repeated char in Java

I have a strange issue to print the first non repeated character from String.
If I put for example "sasso" as String it gives me back correctly: 'a'
but if I try with "sassa" I wonder why it gives me back: "s"
public class FirstChar {
public char findFirst(String s) {
boolean[] letters = new boolean[26];
char[] firstLetter = new char[26];
for (int i = 0; i < s.length(); i++) {
if (letters[s.charAt(i) - 97] &&
(firstLetter[0] != (s.charAt(i)))) {
System.out.println( firstLetter[0]);
return firstLetter[0];
}
letters[s.charAt(i) - 97] = true;
char c = (char) (s.charAt(i));
firstLetter[i] = c;
}
System.out.println(firstLetter[1]);
return firstLetter[1];
}
public static void main(String args[]) {
FirstChar obj = new FirstChar();
obj.findFirst("sassa");
}
}
You need to ensure that firstLetter acts as a queue of non repeating characters and remove from it, the moment repeated character is encountered. You are always returning character at 0th or 1st position without overwriting firstLetter array elements.
In case is sassa, when last character a is encountered, conditions in first if evaluate to true and thus return s which is the first character stored in the firstLetter array.
You need HashMap and Queue to achieve this

why my code is not turn out the result that I want?

I want to define a method that input a string then return a string which character in it has been convert
public static String encode(String s){
char[] newArray = {'a','b','c','d','e','f','g','h','i','g','k','l','m'};
char[] newArray2 = {'n','o','p','q','r','s','t','u','v','w','s','y','z'};
for(int i=0; i<s.length();i++){
if(s.charAt(i) == newArray[i]){
s.replace(newArray[i], newArray2[i]);
}
}
return s;
}
public static void main(String[] args){
System.out.println(encode("firefly"));
}
but compiler just return firefly, I know there is a problem in s.charAt(i) == newArray[i] but how to define a method , for example, 'f' this single char to search through out the newArray, instead of if f correspond the first char at newArray? also how to define it when I want uppercase letter switch only with uppercase . then if I input a String like FireFly it will return SverSyl?
Because replace doesn't change the original String. It returns a new String. You need to write
s = s.replace(newArray[i], newArray2[i]);
to assign the modified String back to the variable s.
First, strings in Java are immutable. This mean you can't change them. What you can is create a new one. Second, you compare your string with the translation array to find a match at the same index. It's very difficult to find a match at the same positions and it's not what you want.
You could use the following method:
public static String encode(String s) {
StringBuffer b = new StringBuffer();
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if ((c >= 'a' && c <= 'm') || (c >= 'A' && c <= 'M')) {
b.append((char) ((int) c + 13));
continue;
}
if ((c >= 'n' && c <= 'z') || (c >= 'N' && c <= 'Z')) {
b.append((char) ((int) c - 13));
continue;
}
b.append(c);
}
return b.toString();
}
The idea is that you translate each character independently and add it to a string buffer. Then you return the resulting string. To transform a character between 'a' and 'm' you just add 13 to its integer code. To transform a character between 'n' and 'z' you just remove 13 from its integer code. You do the same thing for the capital letters.
When we call this method with "FireFly you were cancelled too soon"
public static void main(String args[]) {
System.out.println(encode("FireFly you were cancelled too soon"));
}
the result is:
SverSyl lbh jrer pnapryyrq gbb fbba
Strings are immutable. So technically you need to create a new object and assign it a reference. You can assign your previous string itself to it:
s = s.replace(newArray[i], newArray2[i]);
At the end of your code you are returning s but it's value has not actually been changed. You need to assign something else to that variable or else you will get the same value you input as the output.

Hex to Binary String Java

I'm making Encryption now, and on the step 7 which i need to make the HEX String Array(which I have transferred from ASCII into a String Array) into Binary String.
public static void main(String[] args) {
System.out.println("HEX to Binary: ");
String[] stringHextoBinary = new String[HS.length]; //HS is the String Array for Hex numbers that i save from last step
StringBuilder builder = new StringBuilder();
int l = 0;
for(String s : HS) {
builder.append(s);
if (s.length()<=1){
stringHextoBinary[l] = HexToBinary(s.charAt(0));
l++;
System.out.print(HexToBinary(s.charAt(0)) + ",");
}else{
stringHextoBinary[l] = HexToBinary(s.charAt(0))+HexToBinary(s.charAt(1));
l++;
System.out.print(HexToBinary(s.charAt(0))+HexToBinary(s.charAt(1))+",");
}
public static String HexToBinary(char Hex) {
int i = Integer.parseInt(Character.toString(Hex), 16);
String Bin = Integer.toBinaryString(i);
return Bin;
}
}
the if statement can be work with HEX when it has one digit or two digits.
But my problem is here that it prints out
HEX to Binary:
11100,111,111,10111,11101,
its losing 0 in it. :(
so that when i encrypt word "apple" , and decrypt it with same code will come back with word "pppxl" :(
Hope I can get answer ASAP and thanks a lot!
Use this method of the Apache commons StringUtils class
public String leftPad(String str, int size, char padding);
after you've converted your number to 0s and 1s. It might look like
String paddedBin = StringUtils.leftPad(bin, 8, '0');
for example. Not sure how many digits you actually want to pad it to.
Instead of your method taking in chars, you can simply have it take in a string and convert it to binary using:
public static void main(String[] args) {
System.out.println("HEX to Binary: ");
String[] stringHextoBinary = new String[HS.length]; //HS is the String Array for Hex numbers that i save from last step
// creates the string builder, count, and declaration
StringBuilder builder = new StringBuilder();
int l = 0;
string binaryDigits;
// iterates through string array and appends to string that's being built
// (for whatever reason)
for(String s : HS) {
builder.append(s);
binaryDigits = HexToBinary(s);
stringHextoBinary[l++] = binaryDigits;
System.out.print(binaryDigits);
}
// transforms hex string to binary string without losing 0's
public static String HexToBinary(String Hex) {
string toReturn = new BigInteger(Hex, 16).toString(2);
return String.format("%" + (Hex.length*4) + "s", toReturn).replace(' ', '0')
}
You don't need to combine code, as this is all the code that you need to convert a string to a binary string separated by spaces. It will iterate through and change every string to a binary string.
Try this method implementation:
public static String hexCharToBinary(char c) {
final int v;
if (c >= '0' && c <= '9') {
v = c - '0';
} else if (c >= 'A' && c <= 'F') {
v = 10 + c - 'A';
} else if (c >= 'a' && c <= 'f') {
v = 10 + c - 'a';
} else {
throw new IllegalArgumentException();
}
return String.format("%4s", Integer.toBinaryString(v & 0xFF)).replace(' ', '0');
}
Try this out:
stringHextoBinary[l] = new BigInteger(s,16).toString(2);
What this is doing is creating a new Integer with radix of 16 for you hex numbers and then converting that to a string of base 2 (binary). Haven't tested this out since I am not near a computer with a jvm installed but this is just an idea since you seem to need ideas in a hurry.
This should work too:
stringHextoBinary[l] = Integer.toBinaryString(Integer.parseInt(s, 16));

Creating a string character by character in Java

So I have created this program:
class Input {
public static void main(String[] args) throws Exception {
String hexa;
hexa = "";
int pituus;
pituus = hexa.length();
int i = 1;
char luku;
char luku2;
while (i < pituus) {
luku = hexa.charAt(i);
luku2 = hexa.charAt(i - 1);
luku++;
if (luku == 'G') {
luku = '0';
luku2++;
} else if (luku == ':')
luku = 'A';
if (luku2 == '8')
luku2 = '0';
System.out.print(luku2);
System.out.print(luku);
i += 2;
}
System.out.println();
}
}
As you can propably tell, it prints the original hex string, but adds 1 to every pair of characters, and I want the maximum value of the pairs to be 7F. This program however is only beginning, and to proceed further I need a string with all the characters printed. Is that possible?
To create Strings dynamically you can use StringBuilder. Just append characters to it like
StringBuilder sb = new StringBuilder();// builder is empty now
// some logic
for (char ch = 'a'; ch <= 'z'; ch++) {
// for this example we will just add all lower-case
// characters to builder
sb.append(ch);
}
// after all characres are placed in builder
// lets convert it to string
String alphabet = sb.toString();
// and see what we got
System.out.println(alphabet);
Output: dynamically generated alphabet
abcdefghijklmnopqrstuvwxyz

Categories

Resources