How do I send a string to a char array in Java? - java

String product = Integer.toString(w);
char[] original = String.toCharArray(product);
This is the code I have so far. The error says that I can't use toCharArray on String, but I looked in the documentation, and it is a listed method, so I'm kind of stuck.

product.toCharArray()
The toCharArray is not a static method, but is a method of a string that already exists, which is why it didn't compile for you.
Here is a longer example:
public class ToCharArrayString {
public static void main(String args[]) {
//method converts complete String value to char array type value
String str = " einstein relativity concept is still a concept of great discussion";
char heram[] = str.toCharArray();
// complete String str value is been converted in to char array data by
// the method
System.out.print("Converted value from String to char array is: ");
System.out.println(heram);
}
}

If the original reason was to reverse a number, my sugguestion is
StringBuffer sb = new StringBuffer(Integer.toString(w)); System.out.println(sb.reverse().toString());

Related

How to replace specific characters in a string depending on a users guess [duplicate]

I'm trying to replace a character at a specific index in a string.
What I'm doing is:
String myName = "domanokz";
myName.charAt(4) = 'x';
This gives an error. Is there any method to do this?
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');
System.out.println(myName);
Turn the String into a char[], replace the letter by index, then convert the array back into a String.
String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);
String is an immutable class in java. Any method which seems to modify it always returns a new string object with modification.
If you want to manipulate a string, consider StringBuilder or StringBuffer in case you require thread safety.
I agree with Petar Ivanov but it is best if we implement in following way:
public String replace(String str, int index, char replace){
if(str==null){
return str;
}else if(index<0 || index>=str.length()){
return str;
}
char[] chars = str.toCharArray();
chars[index] = replace;
return String.valueOf(chars);
}
As previously answered here, String instances are immutable. StringBuffer and StringBuilder are mutable and suitable for such a purpose whether you need to be thread safe or not.
There is however a way to modify a String but I would never recommend it because it is unsafe, unreliable and it can can be considered as cheating : you can use reflection to modify the inner char array the String object contains. Reflection allows you to access fields and methods that are normally hidden in the current scope (private methods or fields from another class...).
public static void main(String[] args) {
String text = "This is a test";
try {
//String.value is the array of char (char[])
//that contains the text of the String
Field valueField = String.class.getDeclaredField("value");
//String.value is a private variable so it must be set as accessible
//to read and/or to modify its value
valueField.setAccessible(true);
//now we get the array the String instance is actually using
char[] value = (char[])valueField.get(text);
//The 13rd character is the "s" of the word "Test"
value[12]='x';
//We display the string which should be "This is a text"
System.out.println(text);
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
You can overwrite a string, as follows:
String myName = "halftime";
myName = myName.substring(0,4)+'x'+myName.substring(5);
Note that the string myName occurs on both lines, and on both sides of the second line.
Therefore, even though strings may technically be immutable, in practice, you can treat them as editable by overwriting them.
First thing I should have noticed is that charAt is a method and assigning value to it using equal sign won't do anything. If a string is immutable, charAt method, to make change to the string object must receive an argument containing the new character. Unfortunately, string is immutable. To modify the string, I needed to use StringBuilder as suggested by Mr. Petar Ivanov.
You can overwrite on same string like this
String myName = "domanokz";
myName = myName.substring(0, index) + replacement + myName.substring(index+1);
where index = the index of char to replacement.
index+1 to add rest of your string
this will work
String myName="domanokz";
String p=myName.replace(myName.charAt(4),'x');
System.out.println(p);
Output : domaxokz

Why we can't add character at certain position by charAt(index) in java

public class ReverseString {
public static void main(String[] args) {
String s = "mnop";
s.charAt(0) = 'l';
}
}
Java only allows you to assign to variables, fields and array elements.
The result of a method - like s.charAt(0) - is none of these, so you can't assign to it.
The reason for this is down to the way Java returns: it returns by value, not by reference, and that value only exists temporarily. As such, if you were able to assign it, the side effect of that assignment is immediately lost, making it pointless.
It's also true that String is immutable; but this limitation on what you can assign to is the reason you couldn't do this even for some notional MutableString class you might try to create.
Strings in java are immutable, meaning they can't change at all.
To do something like this, use a StringBuilder:
StringBuilder sb = new StringBuilder("mnop");
sb.setCharAt(0, 'l');
//later, you probably want to get back to a String:
String s = sb.toString();
s.charAt(0) returns a char value, not a char variable to which you could assign a value.
And anyway, String is immutable, so you can't modify the value of an existing String.
You can obtain a copy of the array of all the characters of the String, and modify that array:
String s = "mnop";
char[] chars = s.toCharArray();
chars[0]= 'l';
However, this doesn't modify the original String, since it's immutable.
You can create a new String using that array though:
String newS = new String(chars);
charAt returns a char that's a copy of the character at that position in the string. It's not a reference back to the original string, which is immutable.
You could use a StringBuilder instead, though:
StringBuilder sb = new StringBuilder("mnop");
sb.setCharAt(0, 'l');
String s = sb.toString();

String concat doesnt work [duplicate]

I'm trying to replace a character at a specific index in a string.
What I'm doing is:
String myName = "domanokz";
myName.charAt(4) = 'x';
This gives an error. Is there any method to do this?
String are immutable in Java. You can't change them.
You need to create a new string with the character replaced.
String myName = "domanokz";
String newName = myName.substring(0,4)+'x'+myName.substring(5);
Or you can use a StringBuilder:
StringBuilder myName = new StringBuilder("domanokz");
myName.setCharAt(4, 'x');
System.out.println(myName);
Turn the String into a char[], replace the letter by index, then convert the array back into a String.
String myName = "domanokz";
char[] myNameChars = myName.toCharArray();
myNameChars[4] = 'x';
myName = String.valueOf(myNameChars);
String is an immutable class in java. Any method which seems to modify it always returns a new string object with modification.
If you want to manipulate a string, consider StringBuilder or StringBuffer in case you require thread safety.
I agree with Petar Ivanov but it is best if we implement in following way:
public String replace(String str, int index, char replace){
if(str==null){
return str;
}else if(index<0 || index>=str.length()){
return str;
}
char[] chars = str.toCharArray();
chars[index] = replace;
return String.valueOf(chars);
}
As previously answered here, String instances are immutable. StringBuffer and StringBuilder are mutable and suitable for such a purpose whether you need to be thread safe or not.
There is however a way to modify a String but I would never recommend it because it is unsafe, unreliable and it can can be considered as cheating : you can use reflection to modify the inner char array the String object contains. Reflection allows you to access fields and methods that are normally hidden in the current scope (private methods or fields from another class...).
public static void main(String[] args) {
String text = "This is a test";
try {
//String.value is the array of char (char[])
//that contains the text of the String
Field valueField = String.class.getDeclaredField("value");
//String.value is a private variable so it must be set as accessible
//to read and/or to modify its value
valueField.setAccessible(true);
//now we get the array the String instance is actually using
char[] value = (char[])valueField.get(text);
//The 13rd character is the "s" of the word "Test"
value[12]='x';
//We display the string which should be "This is a text"
System.out.println(text);
} catch (NoSuchFieldException | SecurityException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
You can overwrite a string, as follows:
String myName = "halftime";
myName = myName.substring(0,4)+'x'+myName.substring(5);
Note that the string myName occurs on both lines, and on both sides of the second line.
Therefore, even though strings may technically be immutable, in practice, you can treat them as editable by overwriting them.
First thing I should have noticed is that charAt is a method and assigning value to it using equal sign won't do anything. If a string is immutable, charAt method, to make change to the string object must receive an argument containing the new character. Unfortunately, string is immutable. To modify the string, I needed to use StringBuilder as suggested by Mr. Petar Ivanov.
You can overwrite on same string like this
String myName = "domanokz";
myName = myName.substring(0, index) + replacement + myName.substring(index+1);
where index = the index of char to replacement.
index+1 to add rest of your string
this will work
String myName="domanokz";
String p=myName.replace(myName.charAt(4),'x');
System.out.println(p);
Output : domaxokz

How to copy a string from certain index to an another string in JAVA

How to copy a String from certain index to an another String in Java
example : String s[] = {"0","a","b","c","d","e"};
Need to copy string s from index 1 - rest to an another string s1 (String s1[])
Kindly, help with this issue
Use Arrays.copyOfRange()
public static void main(String[] args) throws Exception {
String s[] = {"0","a","b","c","d","e"};
String s1[] = Arrays.copyOfRange(s, 1,s.length);// copies content from s 1 index to rest
System.out.println(s1);
}
Use System.arraycopy, which is in the SDK to achieve your result.

Why does String not work as "pass by reference" in spite of being an array of characters

I understand that on passing an array asn argument to a function, and making some change to the elements of the array inside the function, the changes will be reflected in the calling function as well, since arrays operates directly on memory (call by reference)
However, why is it that the same behavior does not apply to Strings? I was expecting Strings as well to work in the same way since a String is basically an array of characters.
Please see my code below.
I pass in a String (character array) as well as an int array in to a function and make some changes in it. On printing these in main, I see that the String remains unaffected whereas the changes to the array are reflected.
import java.util.Arrays;
public class TestString
{
public static void main(String[] args)
{
String s = "hello";
int[] a = new int[5];
Arrays.fill(a, -1);
fun(s,a);
System.out.println(s);
System.out.println(a[0]);
}
static void fun(String s, int[] a)
{
s = "world";
a[0] = 99;
}
}
Output
hello
99
First, the claim that a String is an array of characters is wrong. A String is an object, that has methods and is designed specifically not to allow any changes to be made in it.
Second, what you are doing is not changing some element of the parameter. You are changing the parameter variable. The parameter variable is basically a local variable, which receives a reference to the string that was passed as argument. Doing this:
s = "world";
Is not changing the string that was passed. It replaces contents of the local variable s with a new string. Since Java is always pass by value, this is not reflected outside of the method. It would be the same if you had:
a = new int[30];
inside the method. Outside of it you would still see the 5-element int[] that you passed inside.
a[0] = 99;
Is changing an element inside the array. So it looks at a, checks what it refers to, goes to that referred array, and changes its 0th element.
Since String is designed to be immutable, there is no way to do something similar in it. You can't do something like:
s.setCharacter(0,'a'); // This doesn't exist in Java
But you can do this with mutable objects. For example, if you had:
public static void manipulateStringBuilder( StringBuilder sb ) {
sb.append(": manipulated");
sb = new StringBuilder("New value assigned");
}
Then you could write something like:
StringBuilder sb = new StringBuilder("My string");
System.out.println(sb);
manipulateStringBuilder( sb );
System.out.println(sb);
And the output would be:
My string
My string: manipulated
This is because StringBuilder is a mutable object, combined with the fact that the value that you assigned to sb inside your method is never seen outside of it.
Because Strings in java are immutable. Every "change" done to a string does not changes the original string but creates a new String object.
It is because Strings are immutable. If you want to change the value of the String you should return it from the method and store it in the variable s again.
import java.util.Arrays;
public class TestString
{
public static void main(String[] args)
{
String s = "hello";
int[] a = new int[5];
Arrays.fill(a, -1);
s = fun(s,a);
System.out.println(s);
System.out.println(a[0]);
}
static String fun(String s, int[] a)
{
s = "world";
a[0] = 99;
return s;
}
}
I expect it will be helpful for you!
Java is not call by reference, but call by value, it is just that it passes references as values. More details here.
Strings are immutable, so you can't change the content (the char array) of a String, you can just replace it with a different one, i.e. you are changing the reference. But since the reference is passed by value, the change is not visible outside a method.
Actually you can change the content of String using reflection, which results in very interesting behavior. You use this only when you want to play a prank on a coworker.

Categories