Creating a string character by character in Java - 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

Related

I want to remove the special character and convert the next letter to uppercase "the-stealth-warrior" in Java

public class Main {
public static void main(String[] args) {
String name = "the-stealth-warrior";
for (int i = 0; i < name.length();i++){
if (name.charAt(i) == '-'){
char newName = Character.toUpperCase(name.charAt(i+1));
newName += name.charAt(i + 1);
i++;
}
}
}
}
I try to loop in every char and check if the I == '-' convert the next letter to be uppercase and append to a new String.
We can try using a split approach with the help of a stream:
String name = "the-stealth-warrior";
String parts = name.replaceAll("^.*?-", "");
String output = Arrays.stream(parts.split("-"))
.map(x -> x.substring(0, 1).toUpperCase() + x.substring(1))
.collect(Collectors.joining(""));
output = name.split("-", 2)[0] + output;
System.out.println(output); // theStealthWarrior
I think the most concise way to do this would be with regexes:
String newName = Pattern.compile("-+(.)?").matcher(name).replaceAll(mr -> mr.group(1).toUpperCase());
Note that Pattern.compile(...) can be stored rather than re-evaluating it each time.
A more verbose (but probably more efficient way) to do it would be to build the string using a StringBuilder:
StringBuilder sb = new StringBuilder(name.length());
boolean uc = false; // Flag to know whether to uppercase the char.
int len = name.codePointsCount(0, name.length());
for (int i = 0; i < name.len; ++i) {
int c = name.codePointAt(i);
if (c == '-') {
// Don't append the codepoint, but flag to uppercase the next codepoint
// that isn't a '-'.
uc = true;
} else {
if (uc) {
c = Character.toUpperCase(c);
uc = false;
}
sb.appendCodePoint(c);
}
}
String newName = sb.toString();
Note that you can't reliably uppercase single codepoints in specific locales, e.g. ß in Locale.GERMAN.

How do I replace one character occurrence in a string?

How would I replace a string like "Hello" with "Helko", only replacing the second L but not the first?
Use replaceAll with regular expression:
System.out.println("Hello".replaceAll("((?!^).*?|[^l]*l.*?)l","$1k"));
Simple Approach (based on excluding the second l):
Search for first index of l using indexOf and do another search for l but this time start searching from firstL + 1 which will lead to the second index l if exist!
Do a test if there is second l, If So Exclude the second l by using substring which take only the first part (start from zero till secondL) and second part (start from secondL+1 till the end), Concatenate them with k.
public static String removeSecondL(String str) {
int firstL = str.indexOf('l');
int secondL = str.indexOf('l', firstL+1);
if(secondL != -1) {
String firstPart = str.substring(0, secondL);
String secondPart = str.substring(secondL + 1);
return firstPart + 'k' + secondPart;
}
return str;
}
Tests:
public static void main(String[] args) {
System.out.println(removeSecondL("Hello")); // Helko
System.out.println(removeSecondL("lololo")); // lokolo
System.out.println(removeSecondL("no l")); // no l
}
Another Approach: Convert the String into a char array, and declare a variable lFound gonna look for the first occurrence of letter l, if it found next l will be converted to k and exit the loop by break.
String str = "Hello";
char[] chars = str.toCharArray();
boolean lFound = false;
for (int i = 0; i < chars.length; i++) {
if(lFound) {
if(chars[i] == 'l')
{
chars[i] = 'K';
break;
}
}else {
lFound = chars[i] == 'l'; //if(chars[i] == 'l') lFound = true;
}
}
System.out.println(chars); //HelKo
Lately, I turned to the conversation and I saw you writing:
I wanted to replace one instance of a character with another, like "aaaaa" with "aabaa", where only the third 'a' is replaced with 'b', but not the others.
Just follow second approach I posted with additional tests.
public static char[] removeSpecificChar(String str, char a, char b, int position) {
char[] chars = str.toCharArray();
int pos = 1;
for (int i = 0; i < chars.length; i++) {
if(pos == position) {
if(chars[i] == a)
{
chars[i] = b;
break;
}
}else {
pos += (chars[i] == a) ? 1 : 0;
}
}
return chars;
}
Test:
String str = "aaaaa";
System.out.println(removeSpecificChar(str, 'a', 'b', 3));
Print:
aabaa

How to convert a string to uppercase without using the toUpperCase method?

I'm a beginner at java and can't get this code to work. What I have to do is convert any inputted string to uppercase without using the toUpperCase string method. This is what I have:
public String toUpperCase(String str)
{
for(int i = 0; i < str.length(); i++)
{
char a = str.charAt(i);
a = Character.toUpperCase(a);
str += Character.toString(a);
}
return str;
}
You are using str as input, and output (so your String has infinite length, as you keep adding characters). And you can use static, because you aren't using instance state. And, you might use a for-each loop. Finally, add another String, or better a StringBuilder like
public static String toUpperCase(String str) {
StringBuilder sb = new StringBuilder();
for (char ch : str.toCharArray()) {
sb.append(Character.toUpperCase(ch));
}
return sb.toString();
}
There is the following way, but it doesn't consider any characters outside of English (no diacritics, no other language’s characters behind a-z).
public String toUpperCase(String str) {
char[] chars = str.toCharArray();
for (int i=0; i<chars.length; i++) {
char c = chars[i];
if ('a' <= c && c <= 'z') {
chars[i] = (char) (c - 'a' + 'A');
}
}
return new String(chars);
}
I am aware your school probably do not allow you to use StringBuilder and in case you can't use array as well. This is another primitive approach which your school may accept:
public static String toUpperCase(String s){
String str = "";
for(int x=0; x<s.length(); x++){
char ch = s.charAt(x);
if(ch >= 'a' && ch <= 'z')
str += "" + (char)(ch - 32);
else
str += "" + ch;
}
return str;
}
Test:
System.out.println(toUpperCase("aAbBcC"));
Output:
AABBCC
Since you can't use the toUpperCase() method, you can use the ASCII table to get from a lower case letter to an upper case letter by subtracting 32.
'a' = 97, 'A' = 65
'b' = 98, 'B' = 66
...
'z' = 122, 'Z' = 90
public static int DIFF = 'a' - 'A'; // 32
public static String toUpperCase(String str) {
StringBuilder sb = new StringBuilder();
for (char c : str.toCharArray()) {
if (Character.isLowerCase(c)) {
sb.append(String.valueOf((char)(c - DIFF)));
} else {
sb.append(c);
}
}
return sb.toString();
}
try it:
public static String toUpperCase(String str) {
String result = "";
for (int i = 0; i < str.length(); i++) {
int v = str.charAt(i);
if (v > 96 && v < 123) {
v -= 32;
}
result+=(char)v;
}
return result;
}
C'mon guys, Java 8 has been out for years!
/**
* Converts an all-lowercase String to
* uppercase. Retains only spaces, any
* other characters will be lost.
*/
public static String toUpperCase(String s) {
int diff = 'a' - 'A'; // 32
return s.chars()
.filter(c -> c >= 'a' && c <= 'z' || c == ' ')
.mapToObj(c -> String.valueOf((char) (c - (diff))))
.collect(Collectors.joining());
}

Java character to String

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).

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));

Categories

Resources