Take the example:
System.out.println("Hello Uni\u03C0");
System.out.println("Hello Esc \\");
this gives something like
Hello Uniπ
Hello Esc \
Is there a way where I can give different values to 03C0 and \ during different iterations in a loop?
for example
something like
System.out.format("Hello Esc \%c",'\\');
System.out.format("Hello Esc \%c",'\"');
I know this will give compiler error. I want to know how this can be done.
For example, I would like to print a different unicode character (say from \u0000 to \u00C3) in each iteration of a loop.
For example, I have this function that returns the 4 digit hexadecimal value of an integer:
public static String hexa(int a)
{
int x=a;
String b= String.format("%x",x);
if(b.length() == 1)
{
b="000"+b;
}
if(b.length() == 2)
{
b="00"+b;
}
if(b.length() == 3)
{
b="0"+b;
}
return b;
}
Now I would like to join \u with hexa(i) to get different unicode character for different i
You don't even have to convert the integer to hex string. Leave it as an integer and use Character.toChars()
StringBuilder sb = new StringBuilder();
sb.append(Character.toChars(0x03C0));
System.out.println(sb.toString());
Further example showing a for loop:
public static void main(String [] args) {
String lineSeparator = System.lineSeparator();
StringBuilder sb = new StringBuilder();
for(int i = 0x03C0; i < 0x03D0; i++) {
sb.append(Character.toChars(i)).append(lineSeparator);
}
System.out.println(sb.toString());
}
Output:
π
ρ
ς
σ
τ
υ
φ
χ
ψ
ω
ϊ
ϋ
ό
ύ
ώ
Ϗ
One last clarification:
System.out.println(Character.toChars(0x03C0)[0] == '\u03C0');
Output:
true
Example without StringBuilder:
String foo = "";
for(char c : Character.toChars(0x03C0)) {
foo += c;
}
System.out.println(foo);
Related
This is an interview which was asked recently.
Suppose there are 2 strings.
String a="test";
String b="lambda";
Reverse the String.
//tset
//adbmal
Expected output should be : tasdebtmal
Here we are trying to print characters from each string.
"t" from 1st String is printed, followed by "a" from other string, and so on.
So, "tasdebtm" is printed from each string and the remaining characters "al" is appended at the end.
int endA = a.length() - 1;
int endB = b.length() - 1;
StringBuilder str = new StringBuilder();
//add values to str till both the strings are not covered
while(endA>-1 && endB>-1){
str.append(a.charAt(endA--));
str.append(b.charAt(endB--));
}
add all chars of a if any is remaining
while(endA>-1){
str.append(a.charAt(endA--));
}
add all chars of b if any is remaining
while(endB>-1){
str.append(b.charAt(endB--));
}
System.out.println(str);
Definitely, there are other ways to do this too.
public class CharsinString2 {
public static void main(String[] args) {
String a="abra"; //arba
String b="kadabra";//arbadak // aarrbbaadak
int endA=a.length()-1;
int endB=b.length()-1;
StringBuilder str=new StringBuilder();
while(endA>-1 && endB>-1) {
str.append(a.charAt(endA--));
str.append(b.charAt(endB--));
}
while(endA>-1) {
str.append(a.charAt(endA--));
}
while(endB>-1) {
str.append(b.charAt(endB--));
}
System.out.println(str);
}
}
I'm trying to print out a string with spaces on either side of each char in the string
so if I have
String s = "abcde"
it would create something like this
a b c d e
with a space before the first char and three between each char.
I just haven't been able to find a way to do this with my knowledge.
Update
Updated requirement:
I failed to realize that I need something that add one place in front
of the first term and then 3 spaces between each term.
_0___0___0___0___0_ for example.
For the updated requirement, you can use yet another cool thing, String#join.
public class Main {
public static void main(String[] args) {
String s = "abcde";
String result = "_" + String.join("___", s.split("")) + "_";
System.out.println(result);
}
}
Output:
_a___b___c___d___e_
Original answer
There can be so many ways to do it. I find it easier to do it using Regex:
public class Main {
public static void main(String[] args) {
String s = "abcde";
String result = s.replaceAll(".", " $0 ");
System.out.println(result);
}
}
Output:
a b c d e
The Regex, . matches a single character and $0 replaces this match with space + match + space.
Another cool way is by using Stream API.
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String s = "abcde";
String result = Arrays.stream(s.split(""))
.map(str -> " " + str + " ")
.collect(Collectors.joining());
System.out.println(result);
}
}
Output:
a b c d e
A super simple example, that doesn't handle a multitude of potential input scenarios.
public static void main(String[] args)
{
String s = "abcde";
for (int i = 0; i < s.length(); ++i) {
System.out.print("_" + s.charAt(i));
}
System.out.println("_");
}
NOTE: used an underscore rather than a space in order to allow visual check of the output.
Sample output:
_a_b_c_d_e_
Rather than direct output, one could use a StringBuilder and .append to a builder instead, for example.
Using StringBuilder:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); ++i) {
sb.append('_').append(s.charAt(i));
}
sb.append('_');
System.out.println(sb.toString());
Based on a comment where the desired output is slightly different (two internal spaces, one leading and trailing space), this suggests an alternative approach:
public static String addSpace(String inp) {
StringBuilder sB = new StringBuilder();
String string = inp.trim();
String div = "___"; // spaces, or whatever
sB.append('_'); // add leading space
for(int index = 0; index < string.length(); ++index) {
sB.append(string.charAt(index))
.append(div); // two spaces
}
sB.setLength(sB.length() - (div.length() - 1) );
return (sB.toString());
}
NOTE: again using an underscore to allow for easier debugging.
Output when div is set to 3 underscores (or spaces):
_0___0___0___1___0___1___1___0_
You can define an empty string : result = “”;
Then go through the string you want to print with foreach loop With the function toCharArray()
(char character : str.toCharArray())
And inside this loop do ->
result += “ “ + character;
String result = s.chars().mapToObj(
Character::toString
).collect(Collectors.joining(" "));
Similar to the loop versions, but uses a Stream.
Another one liner to achieve this, by splitting the String into String[] of characters and joining them by space:
public class Main {
public static void main(String[] args) {
String s = "abcde";
System.out.println(" " + String.join(" ", s.split("")) + " ");
}
}
Output:
a b c d e
Edit:
The above code won't work for strings with Unicode codepoints like "👦ab😊", so instead of splitting on empty string, the split should be performed on regex: "(?<=.)".
public class Main {
public static void main(String[] args) {
String s = "abcde";
System.out.println(" " + String.join(" ", s.split("(?<=.)")) + " ");
}
}
Thanks to #saka1029 for pointing this out.
You can use Collectors.joining(delimiter,prefix,suffix) method with three parameters:
String s1 = "abcde";
String s2 = Arrays.stream(s1.split(""))
.collect(Collectors.joining("_+_", "-{", "}-"));
System.out.println(s2); // -{a_+_b_+_c_+_d_+_e}-
See also: How to get all possible combinations from two arrays?
I have a scenario where characters like below will be coming in the fixed length file
{ABCDEFGHI = This set of characters represents positive numbers 0123456789 respectively
}JKLMNOPQR = This set of characters represents negative numbers 0123456789 respectively
I need to convert them into corresponding number 0123456789(positive and negative) using java.
for example:
45{ should be converted to 450 (as '{' represents positive '0' )
45A should be converted to 451 (as 'A' represents positive '1' )
45B should be converted to 452 (as 'A' represents positive '2' )
45} should be converted to -450 (as '}' represents negative '0' )
45J should be converted to -451 (as 'J' represents negative '1' )
45K should be converted to -452 (as 'K' represents negative '2' )
I am not that good in java so I am using below code to first replace the string containing above mentioned character with the corresponding number using replace function. I know there must be a better way to do that.Can any please suggest me on this.Many thanks in advance.
public static String replaceChar(String str) {
if (str.contains("{")) {
str = str.replace("{", "0");
}
if (str.contains("A")) {
str = str.replace("A", "1");
}
if (str.contains("B")) {
str = str.replace("B", "2");
}
if (str.contains("C")) {
str = str.replace("C", "3");
}
if (str.contains("D")) {
str = str.replace("D", "4");
}
if (str.contains("E")) {
str = str.replace("E", "5");
}
if (str.contains("F")) {
str = str.replace("F", "6");
}
if (str.contains("G")) {
str = str.replace("G", "7");
}
if (str.contains("H")) {
str = str.replace("H", "8");
}
if (str.contains("I")) {
str = str.replace("I", "9");
}
if (str.contains("J")) {
str = str.replace("J", "1");
}
return str;
}
You could map your alphabet to digits as #Tim already showed using the letters as key and digits as values, check for negativity using regex and finaly replace map keys contained in input string with map values:
public static void main(String[] args) throws IOException {
System.out.println(convert("45{"));
System.out.println(convert("45A"));
System.out.println(convert("45B"));
System.out.println(convert("45}"));
System.out.println(convert("45J"));
System.out.println(convert("45K"));
}
public static long convert(String str){
String alphabet = "{ABCDEFGHI}JKLMNOPQR";
Map<String,String> map = Pattern.compile("")
.splitAsStream(alphabet)
.collect(Collectors.toMap(k->k, k->String.valueOf(alphabet.indexOf(k)%10)));
boolean isNegative = false;
if(Pattern.compile("[J-R\\}]+").matcher(str).find()){
isNegative = true;
}
for(String letter : alphabet.split("")){
str = str.replace(letter, map.get(letter));
}
long result = Long.parseLong(str);
return isNegative ? - result: result;
}
We can try iterating over the string, and then use the modulus to compute the numerical value:
String input = "ABCDEFGHIJKLMNOPQR";
StringBuilder sb = new StringBuilder();
for (int i=0; i < input.length(); ++i) {
sb.append(String.valueOf((input.charAt(i) - 'A') % 10));
}
System.out.println(input);
System.out.println(sb.toString());
ABCDEFGHIJKLMNOPQR
012345678901234567
My output does line up exactly with what you have in your question, but your question appears to have some typos in the letter strings.
So i have a program where i want to replace specific characters in the program with other letters. However, when i run this program, it seems to keep reverting the changed characters back. This is the code so far:
public static String changeSample(String sample) {
for (int i = 0; i < sample.length(); i++) {
if (sample.charAt(i) == 'A') {
sample = sample.replace(sample.charAt(i), 'B');
continue;
}
else if (sample.charAt(i) == 'B') {
sample = sample.replace(sample.charAt(i), 'A');
continue;
}
}
return sample;
Is there a way that i can iterate through each character in the string and then check if it is either an A, B, C, D, E, or F and change it to its complimentary letter, i.e. A to B, B to A, C to D, D to C, E to F, F to E.
replace() will return a new String where ALL occurrences of a particular character are changed, not just a character at a particular position. So your problem is that the repeated replace() statements are effectively modifying the values back and forth.
Because a String is immutable, you cannot simply replace its characters with others dynamically. So, convert your code to use a StringBuilder instead.
StringBuilder buildSample = new StringBuilder();
buildSample.append(sample);
Now you can use setCharAt() instead of replace() to change the character at one position at a time.
buildSample.setCharAt(i, 'A');
At the end, you can return buildSample.toString().
As for changing each letter A to F to its complement, if only these six letters are required, a hard-coded function with a switch statement would do. Otherwise you can use a function like complementaryLetter() below, which returns the complement after checking the ASCII value of the character. This will work for all characters. You can add code to handle invalid cases, for non-character input.
A complete working code:
public class Replace {
public static void main(String[] args) {
String s1 = "ABCDEFA";
System.out.println(s1);
s1 = changeSample(s1);
System.out.println(s1);
}
public static char complementaryLetter(char letter) {
char retChar = 'A';
if ((int) letter % 2 == 0)
retChar = (char) ((int)letter - 1);
else
retChar = (char) ((int) letter + 1);
return retChar;
}
public static String changeSample(String sample) {
StringBuilder buildSample = new StringBuilder();
buildSample.append(sample);
for (int i = 0; i < sample.length(); i++) {
buildSample.setCharAt(i, complementaryLetter(sample.charAt(i)));
}
return buildSample.toString();
}
}
Well, this is my first time get here.
I'm trying to figure out the correct way to replace number into letter.
In this case, I need two steps.
First, convert letter to number. Second, restore number to word.
Words list: a = 1, b = 2, f = 6 and k = 11.
I have word: "b a f k"
So, for first step, it must be: "2 1 6 11"
Number "2 1 6 11" must be converted to "b a f k".
But, I failed at second step.
Code I've tried:
public class str_number {
public static void main(String[] args){
String word = "b a f k";
String number = word.replace("a", "1").replace("b","2").replace("f","6").replace("k","11");
System.out.println(word);
System.out.println(number);
System.out.println();
String text = number.replace("1", "a").replace("2","b").replace("6","f").replace("11","k");
System.out.println(number);
System.out.println(text);
}
}
Result:
b a f k
2 1 6 11
2 1 6 11
b a f aa
11 must be a word "k", but it's converted to "aa"
What is the right way to fix this?
Or do you have any other ways to convert letter to number and vice versa?
Thank you.
It would be good to write methods for conversion between number and letter format. I would write some code like this and use it generally instead of hard coding replace each time.
public class test {
static ArrayList <String> letter = new ArrayList<String> ();
static ArrayList <String> digit = new ArrayList<String> ();
public static void main(String[] args) {
createTable();
String test="b a f k";
String test1="2 1 6 11";
System.out.println(letterToDigit(test));
System.out.println(digitToLetter(test1));
}
public static void createTable()
{
//Create all your Letter to number Mapping here.
//Add all the letters and digits
letter.add("a");
digit.add("1");
letter.add("b");
digit.add("2");
letter.add("c");
digit.add("3");
letter.add("d");
digit.add("4");
letter.add("e");
digit.add("5");
letter.add("f");
digit.add("6");
letter.add("g");
digit.add("7");
letter.add("h");
digit.add("8");
letter.add("i");
digit.add("9");
letter.add("j");
digit.add("10");
letter.add("k");
digit.add("11");
letter.add("l");
digit.add("12");
letter.add("m");
digit.add("13");
letter.add("n");
digit.add("14");
letter.add("o");
digit.add("14");
letter.add("p");
digit.add("15");
//Carry so on till Z
}
public static String letterToDigit(String input)
{
String[] individual = input.split(" ");
String result="";
for(int i=0;i<individual.length;i++){
if(letter.contains(individual[i])){
result+=Integer.toString(letter.indexOf(individual[i])+1)+ " ";
}
}
return result;
}
public static String digitToLetter(String input)
{
String[] individual = input.split(" ");
String result="";
for(int i=0;i<individual.length;i++){
if(digit.contains(individual[i])){
result+=letter.get(digit.indexOf(individual[i])) + " ";
}
}
return result;
}
}
I would actually not use replace in this case.
A more generic solution would be to simply convert it to a char and subtract the char a from it.
int n = word.charAt(0) - 'a' + 1;
This should return an int with the value you are looking for.
If you want this to be an string you can easily do
String s = Integer.parseInt(word.charAt(0) - 'a' + 1);
And as in your case you are doing a whole string looping through the length of it and changing all would give you the result
String s = "";
for(int i = 0; i < word.length(); i++) {
if(s.charAt(i) != ' ') {
s = s + Integer.toString(word.charAt(i) - 'a' + 1) + " ";
}
}
and then if you want this back to an String with letters instead
String text = "";
int temp = 0;
for(int i = 0; i < s.length(); i++) {
if(s.charAt(i) == ' ') {
text = text + String.valueOf((char) (temp + 'a' - 1));
temp = 0;
} else if {
temp = (temp*10)+Character.getNumericValue(s.charAt(i));
}
}
You can just reverse the replacement:
String text = number.replace("11","k").replace("2","b").replace("6","f").replace("1","a");
Simplest solution IMO.
When adding other numbers, first replace these with two digits, then these with one.
Replace this:
String text = number.replace("1", "a").replace("2","b").replace("6","f").replace("11","k");
By this:
String text = number.replace("11","k").replace("1", "a").replace("2","b").replace("6","f");
Right now, the first replace you're doing: ("1", "a")
is invalidating the last one: ("11","k")
I think you would need to store the number as an array of ints. Otherwise, there is no way of knowing if 11 is aa or k. I would create a Map and then loop over the characters in the String. You could have one map for char-to-int and one for int-to-char.
Map<Character,Integer> charToIntMap = new HashMap<Character,Integer>();
charToIntMap.put('a',1);
charToIntMap.put('b',2);
charToIntMap.put('f',6);
charToIntMap.put('k',11);
Map<Integer,Character> intToCharMap = new HashMap<Integer,Character>();
intToCharMap.put(1,'a');
intToCharMap.put(2,'b');
intToCharMap.put(6,'f');
intToCharMap.put(11,'k');
String testStr = "abfk";
int[] nbrs = new int[testStr.length()];
for(int i = 0; i< testStr.length(); i++ ){
nbrs[i] = charToIntMap.get(testStr.charAt(i));
}
StringBuilder sb = new StringBuilder();
for(int num : nbrs){
sb.append(num);
}
System.out.println(sb.toString());
//Reverse
sb = new StringBuilder();
for(int i=0; i<nbrs.length; i++){
sb.append(intToCharMap.get(nbrs[i]));
}
System.out.println(sb.toString());
This failed because the replace("1", "a") replaced both 1s with a characters. The quickest fix is to perform the replace of all the double-digit numbers first, so there are no more double-digit numbers left when the single-digit numbers get replaced.
String text = number.replace("11","k").replace("1", "a").
replace("2","b").replace("6","f");