From char array to string | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

From char array to string

hi there so for the past hours ive been trying to figure out how im suppose to do this.. so lets say i have a string. String text = "Hello"; i've made that string into an char array using char[] chars = text.toCharArray(); So you know the sentence is ['h', 'e', 'l','l','o'...] So know i'm trying to add for example plus 2 to each letter using the ascii table. so h becomes j. e becomes g. I hope that makes sense. I've been able to do that using for(char c : chars) { c+=2; system.out.print(c); } the output would be something like jgnnq The problem is i'm using swing for GUI. And i can't use chars. So my idea was to make some kind of loop that converts each char to string. i have to put the new values into a new array. But thats my problem idk how. So the char array{"H","e", "l", "l","o"} becomes a string array{"jgnnq"} (added +2 to each char) if anything doesn't make sense, im happy to provide more information.

26th Jun 2020, 5:34 PM
Jordi
Jordi - avatar
3 Answers
+ 5
Very important thing is that for-each loop can't modify array elements. In your code `char c` is a copy of actual element. If you modify `c` it'll have no effect on original element. https://code.sololearn.com/cxc4aFVsr5Ar/?ref=app This is applicable even if it's array of objects.
26th Jun 2020, 5:48 PM
🇮🇳Omkar🕉
🇮🇳Omkar🕉 - avatar
+ 1
You are a life saviour man. I can't believe i was struggeling so hard for something so simple.
26th Jun 2020, 7:49 PM
Jordi
Jordi - avatar
0
When i try to do what u did i get a duplicate local variable error. But i have the exact code u typed. https://code.sololearn.com/cKkP9DkYC4ca
26th Jun 2020, 6:13 PM
Jordi
Jordi - avatar