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.
Related
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);
}
I am trying to figure out how to write a method that will remove letters in a
string based on another string. The method would end up like so:
removeLetter("file", "fe")
The only thing that should be returned is the string "il". So far I have something like this:
public class h
{
public static void main(String[] args)
{
String a="file";
String b="fe";
char letter;
int i;
int j;
for (letter = 'a'; letter <= 'z'; letter++)
{
for (i=0; i < a.length()-1; i++)
{
for (j=0; j < b.length()-1; j++) // This is the loop i get stuck on
{
char r = b.charAt(j);
char s = a.charAt(i);
if ( letter == r && letter == s);
System.out.print(r + " " + s);
}
}
}
}
}
I know the bottom part is wrong but I am not sure where to go from here.
You can do this with a regular expression:
a.replaceAll("[" + b + "]", "")
This works by constructing a character class like [fe], and replacing characters which match that with the empty string.
Of course, this is a bit of a hack, in that you can easily choose b such that it won't yield a valid regular expression. However, if you know that b will only ever contain letters, this would work.
Here's a pretty simple nested array using a flag boolean :
public static void main(String[] args) {
String a = "file";
String b = "f";
String c = "";
StringBuilder sb = new StringBuilder();
boolean contains;
for (int i = 0 ; i < a.length() ; i++){
contains = false;
for (int j = 0 ; j < b.length() ; j++){
if (a.charAt(i) == b.charAt(j)) contains = true;
}
if (!contains) sb.append(a.charAt(i));
}
System.out.println(sb);
}
It checks every char of the first word with the chars of the second and changes the flag to true if the char is contained in both.
If it is not the case, the char of the first word is added to the new String, if the contrary, nothing happens and we continue to the next char of the first String.
Let's remove all the vowels of this word : Supercalifragilisticexpialidocious
String a = "Supercalifragilisticexpialidocious";
String b = "aeiou";
Here's the output :
Sprclfrglstcxpldcs
I have a question regarding the problem at codingbat in String 3. Question is as follows:
Given a string, look for a mirror image (backwards) string at both the
beginning and end of the given string. In other words, zero or more
characters at the very begining of the given string, and at the very
end of the string in reverse order (possibly overlapping).
For example, the string "abXYZba" has the mirror end "ab"
mirrorEnds("abXYZba") → "ab"
mirrorEnds("abca") → "a"
mirrorEnds("aba") → "aba"
My code is as follows:
public String mirrorEnds(String string) {
if(string.length() <=1) return string;
String x = "";
int y = string.length() - 1;
for(int i = 0; i < string.length()/2; i++)
{
if(string.charAt(i) == string.charAt(y))
{
x+= Character.toString(x.charAt(i));
y--;
}
else
{
return x;
}
}
return string;
}
When I try it for the following:
"xxYxx"
String length is 5 so index from 0-4. If I run it on my code, the logic will be:
i = 0 and y = 4;
string.charAt(i) == string.charAt(y) //true and i++ and y--
string.charAt(i) == string.charAt(y) //true and i++ and y--
//i is == string.length()/2 at this point
But the problem throws me an error saying indexoutofbounds. Why is this the case?
You are accessing the ith character of the wrong string here:
x += Character.toString(x.charAt(i));
The String x is empty at first, so the character at index 0 doesn't exist.
Access the original string instead.
x += Character.toString(string.charAt(i));
Here my code for this problem , simple one
public String mirrorEnds(String string) {
int start = 0;
int end = string.length()-1;
for(int i=0;i<string.length();i++){
if(string.charAt(start) == string.charAt(end) ){
start++;
end--;
}
if(start != ((string.length()-1)-end)){
break;
}
}
return string.substring(0,start);
}
public String mirrorEnds(String string) {
String g="";
for(int i=0;i<string.length();i++){
if(string.charAt(i)==string.charAt(string.length()-1-i)){
g=g+string.charAt(i);
} else{
break;
}
}
return g;
}
You have a good start, but I think you should consider an even simpler approach. You only need to use one index (not both i and y) to keep track of where you are in the string because the question states that overlapping is possible. Therefore, you do not need to run your for loop until string.length() / 2, you can have it run for the entire length of the string.
Additionally, you should consider using a while loop because you have a clear exit condition within the problem: once the string at the beginning stops being equal to the string at the end, break the loop and return the length of the string. A while loop would also use less variables and would reduce the amount of conditional operators in your code.
Here's my answer to this problem.
public String mirrorEnds(String string) {
String mirror = "";
int i = 0;
while (i < string.length() && string.charAt(i) == string.charAt(string.length() - i - 1) {
mirror += string.charAt(i);
i++;
}
return mirror;
}
Another handy tip to note is that characters can be appended to strings in Java without casting. In your first if statement within your for loop, you don't need to cast x.charAt(i) to a string using Character.toString(), you can simply append x.charAt(i) to the end of the string by writing x += x.charAt(i).
public String mirrorEnds(String str) {
StringBuilder newStr = new StringBuilder();
String result = "";
for (int i=0; i <= str.length(); i++){
newStr.append(str.substring(0, i));
if (str.startsWith(newStr.toString()) && str.endsWith(newStr.reverse().toString()))
result = str.substring(0, i);
newStr.setLength(0);
}
return result;
}
public String mirrorEnds(String string) {
// reverse given string
String reversed = "";
for (int i = string.length() - 1; i >= 0; i--) {
reversed += string.charAt(i);
}
// loop through each string simultaneously. if substring of 'string' is equal to that of 'reversed',
// assign the substring to variable 'text'
String text = "";
for (int i = 0; i <= string.length(); i++) {
if (string.startsWith(string.substring(0, i)) ==
string.startsWith(reversed.substring(0, i))) {
text = string.substring(0, i);
}
}
return text;
}
public String mirrorEnds(String string) {
String out = "";
int len = string.length();
for(int i=0,j = len-1;i<len;i++,j--)
{
if(string.charAt(i) == string.charAt(j))
out += string.charAt(i);
else
break;
}
return out;
}
Scanner _in = new Scanner(System.in);
System.out.println("Enter an Equation of variables");
String _string = _in.nextLine();
char[] cArray = _string.toCharArray();
I want to remove the symbols "+,=" and I want to remove any repeating variables.
so far I have:
for(int i = 0; i < cArray.length; i++){
if(cArray[i].equals(+)|| cArray[i].equals(=)){
cArray[i] = null;
}
}
However, I dont know how to condence the array to remove any gaps and I don't know how to remove repeating characters, I think I am making this harder than it needs to be
You can use:
_string.replaceAll("[+,=]","");
This sounds like a good use for regular expressions:
String result = _string.replaceAll("[+=]", "");
Here, the [+=] is a character class that consists of + and =. You can add other characters as required.
Try the next:
public static void main(String[] args) {
String input = "a+a+b=c+d-a";
char[] cArray = input.replaceAll("[-+=]", "") // gaps
.replaceAll("(.)(?=.*\\1)", "") // repeating
.toCharArray();
System.out.println(Arrays.toString(cArray));
}
Output:
[b, c, d, a]
Or you can se another array, like this:
Scanner in = new Scanner(System.in);
String s = in.nextLine();
char [] cArray = s.toCharArray();
int count = 0;
char [] cArray2 = new char[cArray.length];
for (int i = 0; i < cArray.length; i++){
if (cArray[i] != '+' || cArray[i] != '='){
cArray2[count++] = cArray[i];
}
}
for (int i = 0; i < count; i++){
boolean repeated = false;
for (int j = i + 1; j < count; j++){
if (cArray2[i] == cArray2[j]){
repeated = true;
break;
}
}
if (!repeated){
//do what you want
}
}
You can extend LinkedHashSet (Which enforces uniqueness and retains order). Override the add() function to not accept any characters that you don't want to use. Then put the contents in a char array.
public static char[] toCharArray(String str) {
// Here I am anonymously extending LinkedHashSet
Set<Character> characters = new LinkedHashSet<Character>() {
// Overriding the add method
public boolean add(Character character) {
if (!character.toString().matches("[\\+=]")) {
// character is not '+' or '='
return super.add(character);
}
// character is '+' or '='
return false;
}
};
// Adding characters from str to the set.
// Duplicates, '+'s, and '='s will not be added.
for (int i = 0; i < str.length(); i++) {
characters.add(str.charAt(i));
}
// Put Characters from set into a char[] and return.
char[] arrayToReturn = new char[characters.size()];
int i = 0;
for (Character c : characters) {
arrayToReturn[i++] = c;
}
return arrayToReturn;
}
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