I'm trying to make a program that takes a string and shifts the letters int it by 3 positions.
Example:
Input "AGZ"
Output:"DKC"
I've tried looking at oracles String document about this but I couldn't find anything that I could use. Any tips?
All chars correspond to an int value based on ASCII, so you can do something like this:
String input = "AGZ";
String output = "";
for (char c : input.toCharArray())
output += (char) (c + 3);
Note that this doesn't wrap the Z around to a C, but I wouldn't want to take all the fun from ya.
Related
I'm trying to replace all words (alphabet letters) from JList1 to the number corresponding its place in the alphabet to JList2 with the press of the Run button. (ex. A to 01) And if it's not an English alphabet letter then leaving it as it is. Capitalization doesn't matter (a and A is still 01) and spaces should be kept.
For visual purposes:
"Apple!" should be converted to "0116161205!"
"stack Overflow" to "1920010311 1522051806121523"
"über" to "ü020518"
I have tried a few methods I found on here, but had zero clue how to add the extra 0 in front of the first 9 letters or keep the spaces. Any help is much appreciated.
Here is a solution :
//Create a Map of character and equivalent number
Map<Character, String> lettersToNumber = new HashMap<>();
int i = 1;
for(char c = 'a'; c <= 'z'; c++) {
lettersToNumber.put(c, String.format("%02d", i++));
}
//Loop over the characters of your input and the corresponding number
String result = "";
for(char c : "Apple!".toCharArray()) {
char x = Character.toLowerCase(c);
result+= lettersToNumber.containsKey(x) ? lettersToNumber.get(x) : c;
}
Input, Output
Apple! => 0116161205!
stack Overflow => 1920010311 1522051806121523
über => ü020518
So given...
(ex. A to 01) And if it's not an English alphabet letter then leaving it as it is. Capitalization doesn't matter (a and A is still 01) and spaces should be kept.
This raises some interesting points:
We don't care about non-english characters, so we can dispense with issues around UTF encoding
Capitalization doesn't matter
Spaces should be kept
The reason these points are interesting to me is it means we're only interested in a small subset of characters (1-26). This immediately screams "ASCII" to me!
This provides an immediate lookup table which doesn't require us to produce anything up front, it's immediately accessible.
A quick look at any ascii table provides us with all the information we need. A-Z is in the range of 65-90 (since we don't care about case, we don't need to worry about the lower case range.
But how does that help us!?
Well, this now means the primary question becomes, "How do we convert a char to an int?", which is amazingly simple! A char can be both a "character" and a "number" at the same time, because of the ASCII encoding support!
So if you were to print out (int)'A', it would print 65! And since all the characters are in order, we just need to subtract 64 from 65 to get 1!
That's basically your entire problem solved right there!
Oh, okay, you need to deal with the edge cases of characters not falling between A-Z, but that's just a simple if statement
A solution based on the above "might" look something like...
public static String convert(String text) {
int offset = 64;
StringBuilder sb = new StringBuilder(32);
for (char c : text.toCharArray()) {
char input = Character.toUpperCase(c);
int value = ((int) input) - offset;
if (value < 1 || value > 25) {
sb.append(c);
} else {
sb.append(String.format("%02d", value));
}
}
return sb.toString();
}
Now, there are a number of ways you might approach this, I've chosen a path based on my understanding of the problem and my experience.
And based on your example input...
String[] test = {"Apple!", "stack Overflow", "über"};
for (String value : test) {
System.out.println(value + " = " + convert(value));
}
would produce the following output...
Apple! = 0116161205!
stack Overflow = 1920010311 1522051806121523
über = ü020518
How would I do these problems in CodingBat?
1.When given a char letter you will return the letter that is 10 places away.
tenLettersAway('A') → K
tenLettersAway('B') → L
tenLettersAway('C') → M
2.When given a String word change every letter to a letter that is 10 places away.
wordEncoder("HELLO") → "ROVVY"
wordEncoder("WORLD") → "GYBVN"
wordEncoder("MARY") → "WKBI"
3.When given an array of strings return the concatenation of all the strings separated by spaces.
sumOfArray({"cat", "ate", "dog"}) → "cat ate dog"
sumOfArray({"pig", "sleep", "softly"}) → "pig sleep softly"
sumOfArray({"Mary", "had", "a", "little", "lamb"}) → "Mary had a little lamb"
Thanks!
I don't know whether I should answer this question or not but here's how to do it -
char in java is just treated as a unsigned whole number. Therefore, to get a character 10 places away from it, you can just add 10 to the char. Here's a quick demonstarttion -
char vx = 'a';
vx = vx + 10;
// Now the value of **vx** is **k**
You can use a similar alogrithm to answer your second question like this -
String str = "HELLO"; //Your string
char[] charArray = str.toCharArray(); //Convert it to a character array
Now the array must be like ['H','E','L','L','O']
Now next step is to loop through the array, get a letter 10 characters away and then add it to a string.
Here is how to do it -
String encrypted = "";
for (char elements : charArray) {
encrypted += (elements + 10);
}
The String encrypted should contain the desired encrypted string.
We can use the same trick to answer the third question.
Loop through the array, add the array elements and then separate them using spaces like this -
String myList[] = {"Cat", "ate", "dog"};
String fin = "";
for (String conc : myList) {
fin = fin + conc + " ";
}
//finally remove the last extra space
fin = fin.substring(0, fin.length()-1);
Additional note :
The examples given above may not always works as expected. There might be some cases like this -
char a = 'z';
a = a + 1;
The example given above will not print a but it will print { because it is the next character to z in the Unicode table.
Refer to the ASCII table (or Unicode table for a more broader view) to identify such cases and eliminate them.
Hope it helps
CS student here. I want to write a program that will decompress a string that has been encoded according to a modified form of run-length encoding (which I've already written code for). For instance, if a string contains 'bba10' it would decompress to 'bbaaaaaaaaaa'. How do I get the program to recognize that part of the string ('10') is an integer?
Thanks for reading!
A simple regex will do.
final Matcher m = Pattern.compile("(\\D)(\\d+)").matcher(input);
final StringBuffer b = new StringBuffer();
while (m.find())
m.appendReplacement(b, replicate(m.group(1), Integer.parseInt(m.group(2))));
m.appendTail(b);
where replicate is
String replicate(String s, int count) {
final StringBuilder b = new StringBuilder(count);
for (int i = 0; i < count; i++) b.append(s);
return b.toString();
}
Not sure whether this is one efficient way, but just for reference
for (int i=0;i<your_string.length();i++)
if (your_string.charAt(i)<='9' && your_string.charAt(i)>='0')
integer_begin_location = i;
I think you can divide chars in numeric and not numeric symbols.
When you find a numeric one (>0 and <9) you look to the next and choose to enlarge you number (current *10 + new) or to expand your string
Assuming that the uncompressed data does never contain digits: Iterate over the string, character by character until you get a digit. Then continue until you have a non-digit (or end of string). The digits inbetween can be parsed to an integer as others already stated:
int count = Integer.parseInt(str.substring(start, end));
Here is a working implementation in python. This also works fine for 2 or 3 or multiple digit numbers
inputString="a1b3s22d4a2b22"
inputString=inputString+"\0" //just appending a null char
charcount=""
previouschar=""
outputString=""
for char in inputString:
if char.isnumeric():
charcount=charcount+char
else:
outputString=outputString
if previouschar:
outputString=outputString+(previouschar*int(charcount))
charcount=""
previouschar=char
print(outputString) // outputString= abbbssssssssssssssssssssssddddaabbbbbbbbbbbbbbbbbbbbbb
Presuming that you're not asking about the parsing, you can convert a string like "10" into an integer like this:
int i = Integer.parseInt("10");
I know how to work out the index of a certain character or number in a string, but is there any predefined method I can use to give me the character at the nth position? So in the string "foo", if I asked for the character with index 0 it would return "f".
Note - in the above question, by "character" I don't mean the char data type, but a letter or number in a string. The important thing here is that I don't receive a char when the method is invoked, but a string (of length 1). And I know about the substring() method, but I was wondering if there was a neater way.
The method you're looking for is charAt. Here's an example:
String text = "foo";
char charAtZero = text.charAt(0);
System.out.println(charAtZero); // Prints f
For more information, see the Java documentation on String.charAt. If you want another simple tutorial, this one or this one.
If you don't want the result as a char data type, but rather as a string, you would use the Character.toString method:
String text = "foo";
String letter = Character.toString(text.charAt(0));
System.out.println(letter); // Prints f
If you want more information on the Character class and the toString method, I pulled my info from the documentation on Character.toString.
You want .charAt()
Here's a tutorial
"mystring".charAt(2)
returns s
If you're hellbent on having a string there are a couple of ways to convert a char to a string:
String mychar = Character.toString("mystring".charAt(2));
Or
String mychar = ""+"mystring".charAt(2);
Or even
String mychar = String.valueOf("mystring".charAt(2));
For example.
None of the proposed answers works for surrogate pairs used to encode characters outside of the Unicode Basic Multiligual Plane.
Here is an example using three different techniques to iterate over the "characters" of a string (incl. using Java 8 stream API). Please notice this example includes characters of the Unicode Supplementary Multilingual Plane (SMP). You need a proper font to display this example and the result correctly.
// String containing characters of the Unicode
// Supplementary Multilingual Plane (SMP)
// In that particular case, hieroglyphs.
String str = "The quick brown 𓃥 jumps over the lazy 𓊃𓍿𓅓𓃡";
Iterate of chars
The first solution is a simple loop over all char of the string:
/* 1 */
System.out.println(
"\n\nUsing char iterator (do not work for surrogate pairs !)");
for (int pos = 0; pos < str.length(); ++pos) {
char c = str.charAt(pos);
System.out.printf("%s ", Character.toString(c));
// ^^^^^^^^^^^^^^^^^^^^^
// Convert to String as per OP request
}
Iterate of code points
The second solution uses an explicit loop too, but accessing individual
code points with codePointAt and incrementing the loop index accordingly to charCount:
/* 2 */
System.out.println(
"\n\nUsing Java 1.5 codePointAt(works as expected)");
for (int pos = 0; pos < str.length();) {
int cp = str.codePointAt(pos);
char chars[] = Character.toChars(cp);
// ^^^^^^^^^^^^^^^^^^^^^
// Convert to a `char[]`
// as code points outside the Unicode BMP
// will map to more than one Java `char`
System.out.printf("%s ", new String(chars));
// ^^^^^^^^^^^^^^^^^
// Convert to String as per OP request
pos += Character.charCount(cp);
// ^^^^^^^^^^^^^^^^^^^^^^^
// Increment pos by 1 of more depending
// the number of Java `char` required to
// encode that particular codepoint.
}
Iterate over code points using the Stream API
The third solution is basically the same as the second, but using the Java 8 Stream API:
/* 3 */
System.out.println(
"\n\nUsing Java 8 stream (works as expected)");
str.codePoints().forEach(
cp -> {
char chars[] = Character.toChars(cp);
// ^^^^^^^^^^^^^^^^^^^^^
// Convert to a `char[]`
// as code points outside the Unicode BMP
// will map to more than one Java `char`
System.out.printf("%s ", new String(chars));
// ^^^^^^^^^^^^^^^^^
// Convert to String as per OP request
});
Results
When you run that test program, you obtain:
Using char iterator (do not work for surrogate pairs !)
T h e q u i c k b r o w n ? ? j u m p s o v e r t h e l a z y ? ? ? ? ? ? ? ?
Using Java 1.5 codePointAt(works as expected)
T h e q u i c k b r o w n 𓃥 j u m p s o v e r t h e l a z y 𓊃 𓍿 𓅓 𓃡
Using Java 8 stream (works as expected)
T h e q u i c k b r o w n 𓃥 j u m p s o v e r t h e l a z y 𓊃 𓍿 𓅓 𓃡
As you can see (if you're able to display hieroglyphs properly), the first solution does not handle properly characters outside of the Unicode BMP. On the other hand, the other two solutions deal well with surrogate pairs.
You're pretty stuck with substring(), given your requirements. The standard way would be charAt(), but you said you won't accept a char data type.
You could use the String.charAt(int index) method result as the parameter for String.valueOf(char c).
String.valueOf(myString.charAt(3)) // This will return a string of the character on the 3rd position.
A hybrid approach combining charAt with your requirement of not getting char could be
newstring = String.valueOf("foo".charAt(0));
But that's not really "neater" than substring() to be honest.
It is as simple as:
String charIs = string.charAt(index) + "";
Here's the correct code. If you're using zybooks this will answer all the problems.
for (int i = 0; i<passCode.length(); i++)
{
char letter = passCode.charAt(i);
if (letter == ' ' )
{
System.out.println("Space at " + i);
}
}
if someone is strugling with kotlin, the code is:
var oldStr: String = "kotlin"
var firstChar: String = oldStr.elementAt(0).toString()
Log.d("firstChar", firstChar.toString())
this will return the char in position 1, in this case k
remember, the index starts in position 0, so in this sample:
kotlin would be k=position 0, o=position 1, t=position 2, l=position 3, i=position 4 and n=position 5
CodePointAt instead of charAt is safer to use. charAt may break when there are emojis in the strtng.
CharAt function not working
Edittext.setText(YourString.toCharArray(),0,1);
This code working fine
I come across this question yeasterday and I am aware this has accepted answer, just want to add one more solution to this in javascript scenario which can help people like me who are looking for this -
let name = 'Test'
console.log(name[2])
// Here at index 2 we have 's' value and this will simply give the expected output
Like this:
String a ="hh1hhhhhhhh";
char s = a.charAt(3);
I have to do this for an assignment in my java class. I have been searching for a while now, but only find solutions with regex etc.
For my assignment however I may only use charAt(), length() and/or toCharArray(). I need to get from a string like gu578si300 for example just the numbers so it will become: 578300.
i know numbers are 48 - 57 in ASCII but i can't figure out how to do this in java. You guys any ideas?
i was thinking about a for loop that checks whether the (int) char is between 48-57 en if so puts the value into a seperate array. Howeevr i dont know how to programm that last thing.
I now have this;
public static String filterGetallenreeks(String reeks){
String temp = "";
for (char c : reeks.toCharArray()) {
if ((int) c > 47 && (int) c < 58)
temp += c;
}
return temp;
however it is not working, it just outputs the same as goes in.
is it something in my mainm which looks like this. If i'm right the return temp; will return the temp string into the reeks string in the main right? why is my input still the same a sthe output?
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Voer een zin, woord of cijferreeks in:");
String reeks = sc.nextLine();
if (isGetallenreeks(reeks)){
System.out.println("is getallenreeks");
filterGetallenreeks(reeks);
System.out.println(reeks);
}
Since this is homework I will not be providing the complete solution, however, this is how you should go about it:
Do a for loop that iterates for the total amount of characters within the string (.length). Check if the character is a digit using the charAt and isDigit methods.
You could do a loop that checks a character in the string, and if it's a number, append it to another string:
//I haven't tested this, so you know.
String test = "gu578si300 ";
String numbers = "";
for(int i=0; i<test.length(); i++){
if("0123456789".indexOf(test.charAt(i)) // if the character at position i is a number,
numbers = numbers + test.charAt(i); // Add it to the end of "numbers".
}
int final = Integer.parseInt(numbers); // If you need to do something with those numbers,
// Parse it.
Let me know if that works for you.
It seems like a reasonable approach, but I'd make a couple of changes from what you suggested:
If you need to result as a string then use a StringBuilder instead of an array.
Use character literals like '0' and '9' instead of ASCII codes to make your code more readable.
Update
The specific problem with your code is this line:
temp = temp + (int)c;
This converts the character to its ASCII value and then converts that to a decimal string containing the ASCII value. That's not what you want. Use this instead:
temp += c;