I am working on a ShiftCipher program, and i'm looking to convert a string sentence (" This is an example") to chars, to i can shift the sentence over 2 letters.
Input: "THIS IS AN EXAMPLE"
output:"VJKU KU CP GZCORNG"
with the spaces intact. But i'm not sure how I can convert it to a char, shift the text and then convert it back into a char.
First you have to convert string into char array.
Do this:
String str = "Your input";
char[] charArray = str.toCharArray();
Then you will have to loop through every single char and shift it over by 2.
for(int i = 0; i < charArray.length; i++)
charArray[i] += 2;
And then convert the char array with shifted characters back to string.
String output = new Strin(charArray);
And there you have it.
I do advice you read up on String class but if you do not and simply copy my answer, then no one will cry for you because you fail the class by not putting effort into homework.
Related
I intend to replace strings with normal strings into split strings, but there is a difference in length between the normal strings which amounts to 62 and the split length turns out to be 117, so when we write the 'a' button it doesn't change to 'π' is there another way of writing replace string easier?
public static String doublestruck(String input){
String normal = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
String split = "πππππππππ π‘ππππππππππππ π‘π’π£π€π₯π¦π§π¨π©πͺπ«πΈπΉβπ»πΌπ½πΎβπππππβπβββπππππππβ€";
String output = "";
char letter;
for(int i = 0; i < input.length(); i++){
letter = input.charAt(i);
int a = normal.indexOf(letter);
output += (a != -1) ? split.charAt(a):letter;
}
return new StringBuilder(output).toString();
}
The letters like π (U+1D7DC) are not in the Basic Multilingual Pane and thus take up two char values in Java.
Instead of charAt you need to use codePointAt and to find the correct offset you need to use offsetByCodePoint instead of directly using the same index. So split.charAt(a) needs to be replaced by split.codePointAt(spli.offsetByCodePoint(0, a)).
I am trying to convert String first letter as capital and remaining should be small. I tried below code. It's working fine with convert first letter capital but it's converting remaining letter as small.
String str = "hiGh";
// capitalize first letter
String output = str.substring(0, 1).toUpperCase() + str.substring(1)
Output should be: High
You could manipulate the characters of a String to make sure that only the first one is uppercase,
String capitalizeFirstOf(String s){
char[] chars = s.toCharArray();
for (int i=0; i<s.length(); i++){
if (i==0){
chars[i] = Character.toUpperCase(chars[i]);
}else{
chars[i] = Character.toLowerCase(chars[i]);
}
}
return new String(chars);
}
You need to change the later substring to the lowercase.
Use the following code:
String name = "hiGH";
name = name.substring(0,1).toUpperCase() + name.substring(1).toLowerCase();
If your doing much string converting i would recomend using a libary like:
apache commons 3
They have e.g. UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize etc.
So you don't have to put you time on simple string methods.
I need to replace first and middle char in string but without builder and etc, just with replace but idk how to make it.
String char = JOptionPane.showInputDialog(null, "Input string with more than 3 char");
if (char.length() < 3) {
JOptionPane.showMessageDialog(null, "Wrong input");
I just made this code and that is it, idk how to continue.
Example: input - pniut
I tried with smth like char.length / 2 but cant.
You can convert your string to a character array, and then swap the characters at 0 and middle position. Then convert the array back to String. e.g. I hard coded 2 here but like you mentioned in comments, you will need to figure out the character at the middle position.
String str = "input";
int mid = -1;
if(str.length() % 2 == 0) {
str.length() / 2 - 1
} else {
str.length() / 2;
}
char[] arr = str.toCharArray();
char temp = '0';
temp = arr[0];
arr[0] = arr[mid];
arr[mid] = temp;
String.valueOf(arr);
The value of the middle character, you will need to find out, like you said in the comments.
Since String objects are immutable, converting the original String to a char[] via toCharArray(), replace the characters, then making a new String from char[] via the String(char[]) constructor would work as shown below:
char[] c = character.toCharArray();
// Change characters at desired indicies
c[0] = 'p'; // first character
c[character.length()/2] = 'i'; // approximate middle character
String newString = new String(c);
System.out.println(newString); // "pniut"
Simple answer: not possible (for generic cases).
Meaning: all variants of String.replace() work by replacing one thing with another. There is no notion of using an index anywhere. So you can't say "replace index 1 with A" and "index 3 with B".
The simply solution is to push the string into a char[], to then swap/replace individual characters via index.
I'm betting the goal of the lesson is to learn how to use the API. So would start here Java API. Go to java.lang.String.
I would focus on the .toCharArray() method and the constructor that takes a char[] as an argument. You need to do this because a String is immutable, and cannot be changed. A char[], however can be altered, allowing you to modify the first and middle slots. You can then take your altered array and convert it back into a String.
Hi I am new to Java and am working on a project to get a string split up into individual characters and sent to JavaFX. I imagine the best way is to create an Array for this.
I want to create the array so it has an index of at least the the length of the string and I am getting an error. I then want to send part of the string from a certain point to the end of it to the array. I imagine then I can send the individual letters to JavaFX labels and boxes.
public static void main(String[]args) {
String gamePhrase = "Some Phrase here";
String guessPhrase = gamePhrase.replaceAll("[a-zA-Z0-9]", "*");
System.out.println(guessPhrase);
System.out.println(arraytest);
char[] array2 =new char[gamePhrase.length()];
guessPhrase.getChars (1,gamePhrase.length(),array2,0);
System.out.println(array2);}
}
Where am i going wrong in this ? Why cant I use the the string.length() feature?
Is there are better way any one could suggest? I dont want to use the toArray as the array will not contain all characters.
Any help would be much appreciated.
You can use the string .toCharArray().
char[] array2=gamePhrase.toCharArray()
Then you will have the same as getChars for all the string.
I hope this code will help you.,
String str = "hello";
char[] ch = new char[str.length()];
ch = str.toCharArray();
for(int i=0;i<ch.length;i++){
//this will print all the char
System.out.println("ch len == "+ ch[i]);
//to select specific char
if(ch[i] == 'l'){
System.out.println("selected chars == "+ ch[i]);
}
}
I am having trouble removing letters from a string. String ALPHABET = "abcdefghjklmnopqrstuvwxyz"; User puts in a string. "klmn". How would i remove klmn from the alphabet? Is there a way? Other then putting it into an array?
This is what i started with. This only removes the last letter in the string. Whats my problem here.
for(int i = 0; i < message.length(); i++){
for(int j = 0; j < ALPHABET.length(); j++){
letter = message.charAt(i);
if(ALPHABET.charAt(j) == message.charAt(i)){
newALPHABET = ALPHABET.replace(letter, ' ');
}
}
}
Don't know what you want to do but you can use String#replace
String alphabet = "abcdefghjklmnopqrstuvwxyz";
alphabet = alphabet.replace("klmn","");
Write a method to delete it.. the logic here is replace the char you want to delete with the next char.. and in place of second one keep the third char and so on..
if you want to delete a large length of String..
then use the method Replace..
You can do that with regular expressions. Try the next:
static String ALPHABET = "abcdefghjklmnopqrstuvwxyz";
public static void main(String[] args) {
String input = JOptionPane.showInputDialog("Letters: ");
Pattern p = Pattern.compile("[" + Pattern.quote(input) +"]");
Matcher m = p.matcher(ALPHABET);
String result = m.replaceAll("");
System.out.println(result);
}
If you simply wanted to replace a character or simple substring, then String.replace is the solution.
If you wanted to replace matches a regex, then String.replaceAll is the the solution.
The reason your code is not working is because there are a couple of bugs in it:
You appear to be under the impression that String.replace(char, char) replaces a single character instance. In fact, it replaces all instance of the first character in the String.
Each loop iteration creates a new String and assigns it to newALPHABET. But then you start again with ALPHABET on the next iteration.
If the aim is to produce an "alphabet" that excludes the letters in message, then the correct solution is something like this:
for (int i = 0; i < message.length(); i++) {
ALPHABET = ALPHABET.replace(message.charAt(i), ' ');
}
... except that you should NOT use ALPHABET as the name of a variable. It should be alphabet!!!