Java tells me the charAt method is a variable? - java

Java keeps giving me a compiler error, telling me the charAt method should be a variable and I can't figure out why?
Here's my code:
String s = "12345";
for (int i=0;i<s.length(); i++){
s.charAt(i)= s.charAt((i+1)%s.length());
System.out.println(s);
}
}

s.charAt(i)= s.charAt((i+1)%s.length());
You can't do this in Java. Strings are immutable, and s.charAt(i) evaluates to value, not a variable. This is why it's telling you it should be a variable

Lets say you are doing a rotation cipher.
String s = "12345";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i+1);
ch += 1;
if (ch > '5')
ch -= 5;
sb.append(ch);
}
System.out.println(sb);
String is immutable but StringBuilder is mutable and you can use it to create a new String. Note: the character 1 is the ASCII value of that character or 49. https://en.wikipedia.org/wiki/ASCII so your maths has to take this into account.
If you just want to rotate the characters, you can do
String s2 = s.substring(1) + s.charAt(0);

A Java String is immutable, but there is StringBuilder (which is a mutable sequence of characters). You could do something like,
String str = "12345";
StringBuilder sb = new StringBuilder(str);
for (int i = 0; i < sb.length(); i++) {
sb.setCharAt(i, str.charAt((i + 1) % sb.length()));
}
System.out.println(sb);
I get
23451

s.charAt(i)= s.charAt((i+1)%s.length());, you charAt() returns a character at a particular index , you can't assign to it.

The result of charAt() is a char that cannot be assigned. Moreover, Strings in Java are immutable, meaning that there is no mechanism for changing a string after it has been constructed.
Use StringBuilder to make a new string from the old one character-by-character:
String s = "12345";
StringBuilder res = new StringBuilder("12345");
for (int i=0 ; i<s.length() ; i++) {
res.setCharAt(i, s.charAt((i+1)%s.length()));
}
System.out.println(res);

Or probably you could use an array of char.
char[] s = "12345".toCharArray();
for (int i = 0; i < s.length; i++) {
s[i] = s[(i + 1) % s.length];
System.out.println(s);
}

Related

How to change a char in a String - replacing letters java

Simular topics were not able to solve my problem.
I need to change the char 'a' to 'x' in an given String str.
Example: "abc" = "xbc". I am only allowed to use substring(), charAt() - no replace() method.
My code so far:
public static String ersetze(String text){
for(int i = 0; i<text.length(); i++){
if(text.substring(i, i+1).charAt(i) == 'a'){
text.substring(i, i+1) = 'x';
}
}
//return statement
}
Now the error is text.substring(i, i+1) = 'x';that the left assignment must be a variable - clear. But how to assigne the letter to a variable now? If I declare a char x; how to put that x in the String to replace the letter?
String is immutable in Java, so you cannot replace a letter of a String. You need to create a new String.
You can convert the String to an array of chars and changing only the needed ones, then create a new String from this array:
public static String ersetze(String text){
char[] letters = text.toCharArray();
for (int i = 0; i < letters.length; i++){
if (letters[i] == 'a') {
letters[i] = 'x';
}
}
return new String(letters);
}
String can not replace with character. First Need to create character array & then replace.
public static String ersetze(String text){
char[] result = text.toCharArray();
for(int i = 0; i < result.length; i++){
if(result [i] == 'a'){
result[i] = 'x';
}
}
return String.valueOf(result);
}
If you REALLLLLY need this and you are limited to the methods you mentioned then you can do this each time you find requested char:
text = text.substring(0, i) + x + text.substring(i + 1);
Convert the string to a character array (included in the java API), iterate through the array and replace all the "a"'s with "x"'s in the char array and then change it back to a string.

Best way to concatenate Strings in java(Time efficiency)

I checked many discutions about the best way to concatenate many string In Java.
As i understood Stringbuilder is more efficient than the + operator.
Unfortunantly My question is a litlle bit different.
Given the string :"AAAAA", how can we concatenate it with n times the char '_',knowing that the '_' has to come before the String "AAAAA"
if n is equal to 3 and str="AAAAA", the result has to be the String "___AAAAA"
String str = "AAAAA";
for (int i=0;i<100;i++){
str="_"+str;
}
In my program i have a Longs String , so i have to use the efficient way.
Thank you
EDIT1:
As I have read some Solutions I discovered that I asked for Only One Case , SO I arrived to this Solution that i think is good:
public class Concatenation {
public static void main(String[] args) {
//so str is the String that i want to modify
StringBuilder str = new StringBuilder("AAAAA");
//As suggested
StringBuilder space = new StringBuilder();
for (int i = 0; i < 3; i++) {
space.append("_");
}
//another for loop to concatenate different char and not only the '_'
for (int i = 0; i < 3; i++) {
char next = getTheNewchar();
space.append(next);
}
space.append(str);
str = space;
System.out.println(str);
}
public static char getTheNewchar(){
//normally i return a rondom char, but for the case of simplicity i return the same char
return 'A';
}
}
Best way to concatenate Strings in Java: You don't.... Strings are immutable in Java. Each time you concatenate, you generate a new Object. Use StringBuilder instead.
StringBuilder sb = new StringBuilder();
for (int i=0;i<100;i++){
sb.append("_");
}
sb.append("AAAAA");
String str = sb.toString();
Go to char array, alloting the right size, fill the array, and sum it up back into a string.
Can’t beat that.
public String concat(char c, int l, String string) {
int sl = string.length();
char[] buf = new char[sl + l];
int pos = 0;
for (int i = 0; i < l; i++) {
buf[pos++] = c;
}
for (int i = 0; i < sl; i++) {
buf[pos++] = string.charAt(i);
}
return String.valueOf(buf);
}
I'd do something like:
import java.util.Arrays;
...
int numUnderbars = 3;
char[] underbarArray = new char[numUnderbars];
Arrays.fill(underbarArray, '_');
String output = String.valueOf(underbarArray) + "AAAA";
but the reality is that any of the solutions presented would likely be trivially different in run time.
If you do not like to write for loop use
org.apache.commons.lang.StringUtils class repeat(str,n) method.
Your code will be shorter:
String str=new StringBuilder(StringUtils.repeat("_",n)).append("AAAAA").toString();
BTW:
Actual answer to the question is in the code of that repeat method.
when 1 or 2 characters need to be repeated it uses char array in the loop, otherwise it uses StringBuilder append solution.

How to make alternate characters in a string to uppercase?

I wrote the following code but similar characters are always in the same case. What's wrong in this code and How can this problem be solved??
private void genBTActionPerformed(java.awt.event.ActionEvent evt) {
String str = new String(strTF.getText());
int n = str.length();
char ch;
int i;
for(i = 0; i < n; i++) {
if(i % 2 == 0) {
ch = Character.toLowerCase(str.charAt(i));
str = str.replace(str.charAt(i), ch);
} else {
ch = Character.toUpperCase(str.charAt(i));
str = str.replace(str.charAt(i), ch);
}
}
jumTF.setText(str);
}
Unlike what its name says, .replace() replaces characters/CharSequences in the whole input. The difference with .replaceAll() is that it takes literals as arguments and not regexes/regex replacements strings (and that it has an overload taking two chars as arguments). That is the second worst misnamed method of the String class after matches().
Moreover you create a new String on each character you replace, so you have n+1 strings for a n character long string. Do it like this instead:
final char[] chars = str.toCharArray();
final int len = chars.length;
char c;
for (int i = 0; i < len; i++) {
c = chars[i];
chars[i] = i % 2 == 0
? Character.toLowerCase(c)
: Character.toUpperCase(c);
}
jumTF.setText(new String(chars));
In your program you were using replace() which replaces characters/CharSequences in the whole input what you need to do is
Put the string into an array.
Iterate over said array.
convert that array back into string
private void genBTActionPerformed(java.awt.event.ActionEvent evt) {
String str = new String(strTF.getText());
char [] chr= str.toCharArray();
int n = chr.length;
char ch;
int i;
for(i = 0; i < n; i++) {
if(i % 2 == 0) {
ch = Character.toLowerCase(chr[i]);
chr[i]=ch;
} else {
ch = Character.toUpperCase(chr[i]);
chr[i]=ch;
}
}
jumTF.setText(new String(chr)); }
hope this will help you :)
Since String are immutable in java , you can use StringBuilder or StringBuffer to solve this problem
StringBuilder str=new StringBuilder(inputString);
You can use your own logic just with slight change instead of using
str = str.replace(str.charAt(i), ch);//since it replaces in whole string
Use
str.setCharAt(i,ch);
So your final Program looks like this :
for(i = 0; i < n; i++) {
if(i % 2 == 0) {
ch = Character.toLowerCase(str.charAt(i));
str.setCharAt(i,ch);
} else {
ch = Character.toUpperCase(str.charAt(i));
str.setCharAt(i,ch);
}
}
Suppose InputString is : stackoverflow
then output is : sTaCkOvErFlOw

Trouble using if-statement and String.replace

I have the following snippet for a hangman game I'm developing in Eclipse:
String secret = "apple";
String str = "-----"
for (int i = 0; i < 5; i++) {
if (letter == secret.charAt(i)){
str = str.replace(str.charAt(i), letter);
}
}
System.out.println(str);
Unfortunately, this is printing out
aaaaa
instead of
a----
How would I get this working?
The JavaDoc of String#replace(char, char) states that it will replace all occurrences not just the first.
Since you want to make a hangman game, you need to only replace the positions where letter appears in secret
It might be better to manually replace the characters in a String using a StringBuilder or a char[]
char[] secret="apple".toCharArray();
char[] str= new char[secret.length];
Arrays.fill(str, '-');
for (int i = 0; i < secret.length; i++) {
if (letter ==secret[i]){
str[i] = letter;
}
}
System.out.println(new String(str));
If you want really set only a character in a String, you could do something like this:
StringBuilder sbStr = new StringBuilder(str);
sbStr.setCharAt(4, 'x');
This is your code refactored:
String secret = "apple";
String str = "-----"
StringBuilder sbStr = new StringBuilder(str);
for (int i = 0; i < 5; i++) {
if (letter == secret.charAt(i)){
sbStr.setCharAt(i, letter);
}
}
System.out.println(sbStr.toString());
str.replace(str.charAt(i), letter); will not work because it does not replace a single character, but all charachters in the String matching str.charAt(i), what you could do is use StringBuilders to change the character at a given index, like this:
String secret = "apple";
StringBuilder str = new StringBuilder("-----");
for (int i = 0; i < 5; i++) {
if (letter == secret.charAt(i)){
str.setCharAt(i, letter);
}
}
System.out.println(str.toString()); // Or simply: System.out.println(str);
If you don't want to use StringBuilder, something like this will also work:
String secret = "apple";
String str = "-----";
for (int i = 0; i < 5; i++) {
if (letter == secret.charAt(i)){
str = str.substring(0, i) + secret.charAt(i) + str.substring(i);
}
}
System.out.println(str);
Although I advice a StringBuilder in this case.
Hope this helps.
I suggest to use String builder for both secret and str, and mark guess character in secret too, because your solution may fails for repeating characters
char letter = 'a';
StringBuilder secret = new StringBuilder("apple");
StringBuilder str = new StringBuilder("-----");
int index = secret.indexOf(String.valueOf(letter));
if(index != -1)
{
secret.setCharAt(index, '-');
str.setCharAt(index, letter);
}
System.out.println(secret);
System.out.println(str);
Hopes that Helps

Finding characters in a string

i'm doing an encoding program where i'm supposed to delete every character in the string which appears twice. i've tried to traverse through the string but it hasn't worked. does anyone know how to do this? Thanks.
public static String encodeScrambledAlphabet(String str)
{
String newword = str;
String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
newword += alphabet;
newword = newword.toUpperCase();
for (int i = 0, j = newword.length(); i < newword.length() && j >=0; i++,j--)
{
char one = newword.charAt(i);
char two = newword.charAt(j);
if (one == two)
{
newword = newword.replace(one, ' ');
}
}
newword = newword.replaceAll(" ", "");
return newword;
}
Assuming that you would like to keep only the first occurrence of the character, you can do this:
boolean seen[65536];
StringBuilder res = new StringBuilder();
str = str.toUpperCase();
for (char c : str.toCharArray()) {
if (!seen[c]) res.append(c);
seen[c] = true;
}
return res.toString();
The seen array contains flags, one per character, indicating that we've seen this character already. If your characters are all ASCII, you can shrink the seen array to 128.
Assuming by saying deleting characters that appears twice, you mean AAABB becomes AAA, below code should work for you.
static String removeDuplicate(String s) {
StringBuilder newString = new StringBuilder();
for (int i = 0; i < s.length(); i++) {
String s1 = s.substring(i, i + 1);
// We need deep copy of original String.
String s2 = new String(s);
// Difference in size in two Strings gives you the number of
// occurences of that character.
if(s.length() - s2.replaceAll(s1, "").length() != 2)
newString.append(s1);
}
return newString.toString();
}
Efficiency of this code is arguable :) It might be better approach to count the number of occurences of character by a loop.
So, from the code that you've shown, it looks like you aren't comparing every character in the string. You are comparing the first and last, then the second and next to last. Example:
Here's your string:
THISISTHESTRINGSTRINGABCDEFGHIJKLMNOPQRSTUVWXYZ
First iteration, you will be comparing the T at the beginning, and the Z at the end.
Second iteration, you will be comparing the H and the Y.
Third: I and X
etc.
So the T a the beginning never gets compared to the rest of the characters.
I think a better way to do this would be to to do a double for loop:
int length = newword.length(); // This way the number of iterations doesn't change
for(i = 0; i < length; i++){
for(j = 0; j < length; j++){
if(i!=j){
if(newword.charAt(i) == newword.charAt(j)){
newword.replace(newword.charAt(i), ' ');
}
}
}
}
I'm sure that's not the most efficient algorithm for it, but it should get it done.
EDIT: Added an if statement in the middle, to handle i==j case.
EDIT AGAIN: Here's an almost identical post: function to remove duplicate characters in a string

Categories