This question already has answers here:
Java arrays printing out weird numbers and text [duplicate]
(10 answers)
Closed 8 years ago.
I was trying to implement a string reversal algorithm by using two pointer variables at each end of the string where i points to the beginning and j points to the end. The elements at these places are swapped and then i and j are incremented and decremented respectively until i is less than j and i not equal to j. I am storing the string in a character array while doing this since string is immutable in java. However, when I am trying to convert this character array back to a string using the toString() method it is displaying random values. I know the code is correct since if I output the character array it displays the right values.
public class switcher {
int i=0,j;
char temp;
public void reverse(String s){
char [] ar = s.toCharArray();
j=ar.length-1;
while(i!=j&&i<j){
temp = ar[i];
ar[i]=ar[j];
ar[j]=temp;
i++;
j--;
}
String b=ar.toString();
System.out.println(b);
System.out.println(ar);
}
The output is as follows for the two print statements:
amistad
[C#22a79c31
datsima
As you can see the string output is not correct. However, the array output is perfect.
Please tell me what I am doing wrong.
If you want to print String which should be based on array of character then you should wrap this array with new String object. So instead of
String b = ar.toString();
use
String b = new String(ar);
You need to know that arrays inherit toString() method from Object so its code returns
getClass().getName() + "#" + Integer.toHexString(hashCode());
which means you will see [C as result of getClass().getName() which represents one dimensional array of characters, # token and hexadecimal form of arrays hexcode 22a79c31.
In case you would want to print content of array with different type of data than char you wouldn't be able to wrap it in String. Instead you will have to iterate over each elements and print them. To avoid writing your own method for this Java gives you java.util.Arrays class with toString(yourArray) method which will iterate over each elements of array and generate String in form
[element0, element1, element2, ... , elementN-1]
ar.toString() will not return the string representation of the character array. It will return the index of the array in memory. If you want b to print out properly, pass ar to it as a constructor, like so:
String b = new String(ar);
As others have said, that's correct.
Most Java objects do not do a value conversion in their tostring. Instead they print the tokenized name of the type as known internally to the VM.
To convert a character array to a string for printing you want to do the opposite of what you did to convert it from a string.
The simplest way is simply to make use of the string constructor that takes a character array
So rather then saying:
System.out.println(ar);
You could say
System.out.println(new String(ar));
Related
This question already has answers here:
Get string character by index
(13 answers)
Closed 3 years ago.
here's a sample code I wrote,
public static void main(String []args){
String inputString = "apple";
char a = inputString[2]; //one
System.out.println(inputString[2]); //two
}
both one and two gives me an error saying Array type expected; found: 'java.lang.String' what am I doing wrong? how do I access a specific index in a String?
You are trying to access the String's characters as if it was an array of characters. You should use the charAt method instead:
char a = inputString.charAt(2);
In order for array access to work, you should first obtain the array of characters of the given String:
char[] chars = inputString.toCharArray();
char a = chars[2];
This is useful when iterating over the characters of the String.
You cannot get a character at a given index as you would do for a an array because String isn't an array per say. It is a class.
The method charAt is what you are looking for:
input.charAt(2)
The signature of the method is the following:
public char charAt(int index);
And the javadoc says:
Returns the char value at the specified index. An index ranges from 0 to length() - 1. The first char value of the sequence is at index 0, the next at index 1, and so on, as for array indexing. If the char value specified by the index is a surrogate, the surrogate value is returned.
I am writing an application that stores a series of values in an Array List object. All of the values are stored as Strings in the array, and one of the parameters is a time stamp which is prefixed with "Timestamp: " followed by the actual Unix timestamp (e.g. 1556849753564)
I need to parse only the Unix timestamp from the Timestamp String object.
Here is what I have tried:
public void parseTimestamp() {
String lastBlockTimeAsString = (String) HashArray.hashArray.get(HashArray.hashArray.size() - 12);
char[] timeAsCharArray = lastBlockTimeAsString.toCharArray();
long lastBlockTime = Long.parseLong(String.valueOf(timeAsCharArray[12] + timeAsCharArray[13] ..... etc ));
}
The HashArray.hashArray.get() call is just pulling the Timestamp object from the Array List.
I am pulling the 12th character from the array because that is the start of the timestamp.
In Python I could do something like:
timeAsCharArray[12]:[24]
How can I accomplish this in Java more elegantly than the solution I came up with, which is basically to concatenate each individual character from the array.. Any help would be appreciated!
Not sure why you are trying to convert a string to a character array and then concatenate again. As noted by DevilsHnd, you could either split by removing the "Timestamp: " prefix and getting the "Unix time"
or you could replace and then cast. Remember, this assumes that after the replace, user will always have Long numeric value
long lastBlockTime = Long.parseLong(lastBlockTimeAsString.replace("Timestamp: ",""));
What is the difference between charValue() and toString() methods of class Character. Both of them return the same i.e, the character value held by the object of the class character as in following code.
public class OtherCharMethods
{
public static void main(String[] args)
{
Character c1 = 'A';
Character c2 = 'A';
System.out.printf(
"c1 = %s\nc2 = %s\n\n", c1.charValue(), c2.toString());
if (c1.equals(c2))
System.out.println("c1 and c2 are equal\n");
else
System.out.println("c1 and c2 are not equal\n");
}
} // end class OtherCharMethods
The one method returns a single char value (primitive type); the other one returns a String (reference type).
That is all there is to this.
Given your comment: the thing to understand - that returned string will of course contain exactly one character; the one that charValue() returns to you.
But: those are still two different things. As the literals "a" and 'a' also contain one char; but in the end mean different things. If you just print the variables to System.out; of course that gives the same result. But that doesn't make a char the same as a String.
Character#charValue() returns a char, Character#toString() returns an string OBJECT, that is a huge difference between those two, one is a primitive, the other an object
charValue() will represent certain value of the character and toString() function will convert the value into string. so both the operation are different.. if you try to give more than one character in the charvalue() function's object, it will give a compile time error but in toString() case its different you can pass any kind of object and any number of characters which capable to convert it to string.
I am trying to convert a string to ascii code and then multiplying that concatenation of the ascii codes by a number.
For example
String message = "Hello";
String result = "";
ArrayList arrayList = new ArrayList();
int temp;
for(int i = 0; i < message.length(); i++){
temp = (int) message.charAt(i);
result = result + String.value(temp).toString();
arrayList.add(String.valueOf(temp).toString());
}
I have tried two different ways, but there is always a catch with each one.
If I just concatenate all the ascii codes together into a string and I get 72101108108111 as my new string, the problem now is how can I get the original string back from this? This is because it is not obvious where each one character code starts and ends and the next one begins.
Another way I tried doing this was to use an array. I would receive |72|101|108|108|111| in an array. Obviously the codes are split here, but if I wanted to multiply this whole array (all the numbers as one number) by a number and then how would I get the array back together?
These are two different ways I have thought to solve this, but I have no idea how to get the string back out of these if I multiply the ascii by a number.
You don't need to modify the original string nor the ascii code string. Just have them both there, then whenever you need to get the numerical value of the string, just use X.valueOf(...)** method. Example,
final String message = "Hello";
final String result = "72101108108111";
long value = Long.valueOf(result);
If you do not want to store the two strings, then you should go with the array method. To get a numerical value, you simply concatenate all the strings in the array into one and use the X.valueOf(..) method.
And to get back the original string, use Integer.valueOf(...) on each string in the array, then cast each one to char.
System.out.println((char)Integer.valueOf("111").intValue());
** Note by X.valueOf(..), X doesn't have to be Long or Integer as I have shown. As you mentioned the value can get really large so BigInteger should be prefered above others
i am trying to generate a hex color value from an integer input, and I'm not sure I'm using the concat method correctly. when i output the string theColor, i only get "0x", any ideas?
public String generateColor(String redVal, String blueVal,
String greenVal, String alphaVal){
String theColor = "0x";
theColor.concat(alphaVal);
theColor.concat(redVal);
theColor.concat(greenVal);
theColor.concat(blueVal);
return theColor;
}
You will need to reassign it to the theColor as concat() method returns a string with concatenation.
like
theColor = theColor.concat(alphaVal);
String's concat does not modify the original String (Strings are immutable in Java). I'd suggest using a StringBuilder here:
public String generateColor(String redVal, String blueVal, String greenVal, String alphaVal) {
StringBuilder theColor = new StringBuilder("0x")
.append(alphaVal)
.append(redVal)
.append(greenVal)
.append(blueVal);
return theColor.toString();
}
String objects in java are immutable that is operations like concat do not modify original object but create new. You need modify you code to assign modified value to theColor:
theColor = theColor.concat(alphaVal);
If your input strings are all 2-character strings with two hex digits, then you can generate the string you want really simply:
public String generateColor(String redVal, String blueVal,
String greenVal, String alphaVal) {
return "0x" + alphaVal + redVal + greenVal + blueVal;
}
No need to fool around with StringBuilder or concat.
If the input strings have been converted from integers, so that you're not sure that they are two hex digits, then the above won't work. But solutions using concat or StringBuilder's append won't work either, since they essentially do the same thing as + -- they just concatenate all the strings together.
The first question to ask is, are you converting the integers to Strings too early? If you convert the integers to strings, then you pass the strings as parameters to generateColor, and then you are concerned that the strings aren't already in the right format, then you really ought to be passing your integers to generateColor, instead of the strings, and letting generateColor convert them to the kinds of strings you need. There are several ways to do this; here's one:
public String generateColor(int redVal, int blueVal,
int greenVal, int alphaVal) {
return String.format("0x%02x%02x%02x%02x", alphaVal & 0xFF,
redVal & 0xFF, greenVal & 0xFF, blueVal & 0xFF);
}
%02x says to format the next parameter in hex (the x), into a string 2 characters wide (the 2), and padding with leading zeros instead of blanks if the value is only one hex digit (the 0). If the integer value is too big to fit into two digits, format will include three or more characters in the string, which is why I used & 0xFF on each integer to ensure that the value will not be too big. %02x does not put an 0x at the front. The format string has its own 0x to put those two characters into the result. (If desired, you can use %02X instead of %02x, which causes the hex digits A-F to appear in upper case.)
There are other ways: you could create one int from the four input integers using &, | and << bit operators, and use "0x%08x" as the format string. And there are methods besides String.format that are capable of generating hex integers.