How can I remove characters from a StringBuffer? - java

I am trying to make an encryption program and part of this includes having a passcode displayed at the beginning of my encrypted text and then displaying the alphabet after that with the letters contained in the passcode being removed from the alphabet. I am trying to remove the characters in the passcode from my alphabet StringBuffer but it seems like there is no easy way to do this. There is no method that automatically searches a method for all occurences of a character but there is for a String object. However, I must replace a character with another character and I want to replace a character with nothing(essentially delete it). This is my code: Any help would be appreciated.
StringBuffer alphabet = new StringBuffer("abcdefghijklmnopqrstuvwxyz");
for(int i = 0; i < pass.length(); i++)
{
char replacedletter = pass.charAt(i);
alphabet.replace(replacedletter,"");
}
System.out.println(pass + alphabet);

This might work for you:
StringBuffer s=...
for(char c: passcode.toCharArray()){
int index=-1;
while((index=s.indexOf(c))!=-1){
s.deleteCharAt(index);
}
}

You didn't indicate which version of java you are using but in 7 StringBuffer does have a replace method.
replace(int start, int end, String str)
Replaces the characters in a substring of this sequence with characters in the specified String.
Combine this with the indexOf method to replace all occurrences.
int ndx = alphabet.indexOf(String.valueOf(replacedLetter), 0);
while (ndx > -1) {
alphabet.replace(ndx, ndx + 1, "");
ndx = alphabet.indexOf(String.valueOf(replacedLetter), ndx);
}

Related

I am trying to write a numerify code like in Javafakers API

So, I need to replace '#' in a string with a random number(0-9).
Eg: String: "I am l#earning abou#t Jav#a".
I am expecting an output like "I am l1earning abou5t Jav3a".
From the below code, I am getting an output like
"I am l2earning abou2t Jav2a" where the code is generating random numbers but after reruns.
What changes have to be performed in the code to generate different random numbers in the same string?
Java
import java.util.Random;
public class numerify {
public static void main(String[] args) {
String str = " I am l#earning abo#ut Jav#a.";
String num="1234567890";
Random r= new Random();
int n=num.length();
for (int i = 0; i < str.length() - 1; i++) {
char ran= num.charAt(r.nextInt(n));
if (str.charAt(i) == '#') {
str = str.replace('#',ran);
}
}
System.out.println(str);
}
}
The method replace replaces all occurances.
Try using replaceFirst https://docs.oracle.com/javase/8/docs/api/java/lang/String.html#replaceFirst-java.lang.String-java.lang.String-
str = str.replaceFirst('#',ran);
If the condition is only true for the first time and after that replace will replace all occurrences of #, so there is no # available to replace next time.
You need to replace only one # at a time. Use replaceFirst instead.
if (str.charAt(i) == '#') {
char ran= num.charAt(index);
str = str.replaceFirst("#",Character.toString(ran));
}
ReplaceFirst() needs to be used instead of Replace().
ReplaceFirst()method replaces the first substring of this string that matches the given regular expression with the given replacement.

Replacing a character in a string with another character from another string

I am trying to eventually replace a sentence with another set of String. But I hit a roadblock while trying to replace a char in a String with another character of another String.
Here's what I have so far.
String letters = "abcdefghijklmnopqrstuvwxyz";
String encode = "kngcadsxbvfhjtiumylzqropwe";
// the sentence that I want to encode
String sentence = "hello, nice to meet you!";
//swapping each char of 'sentence' with the chars in 'encode'
for (int i = 0; i < sentence.length(); i++) {
int indexForEncode = letters.indexOf(sentence.charAt(i));
sentence.replace(sentence.charAt(i), encode.charAt(indexForEncode));
}
System.out.println(sentence);
This way of replacing characters doesn't work. Can someone help me?
The reason
sentence.replace(sentence.charAt(i), encode.charAt(indexForEncode));
doesn't work is that Strings are immutable (i.e., they never change).
So, sentence.replace(...) doesn't actually change sentence; rather, it returns a new String. You would need to write sentence = sentence.replace(...) to capture that result back in sentence.
OK, Strings 101: class dismissed (;->).
Now with all that said, you really don't want want to keep reassigning your partially encoded sentence back to itself, because you will, almost certainly, find yourself re-encoding characters of sentence that you already encoded. Best to leave sentence in its original form while building up the encoded string one character at a time like this:
StringBuilder sb = new StringBuilder();
for (int i = 0; i < sentence.length(); i++){
int indexForEncode = letters.indexOf(sentence.charAt(i));
sb.append(indexForEncode != -1
? encode.charAt(indexForEncode)
: sentence.charAt(i)
);
}
sentence = sb.toString();
I would use a character array as follows. Make the changes to a character array and then use String.valueOf to get the new version of the string.
String letters = "abcdefghijklmnopqrstuvwxyz";
String encode = "kngcadsxbvfhjtiumylzqropwe";
// the sentence that I want to encode
String sentence = "hello, nice to meet you!";
char[] chars = sentence.toCharArray();
for (int i = 0; i < chars.length; i++){
int indexForEncode = letters.indexOf(sentence.charAt(i));
// if index is < 0, use original character, otherwise, encode.
chars[i] = indexForEncode < 0 ? chars[i] : encode.charAt(indexForEncode);
}
System.out.println(String.valueOf(chars));
Prints
xahhi, tbga zi jaaz wiq!
You can use codePoints method to iterate over the characters of this string and replace them with characters from another string, if any.
Try it online!
public static void main(String[] args) {
String letters = "abcdefghijklmnopqrstuvwxyz";
String encode = "kngcadsxbvfhjtiumylzqropwe";
String sentence = "hello, nice to meet you!";
String encoded = replaceCharacters(sentence, letters, encode);
String decoded = replaceCharacters(encoded, encode, letters);
System.out.println(encoded); // xahhi, tbga zi jaaz wiq!
System.out.println(decoded); // hello, nice to meet you!
}
public static String replaceCharacters(String text, String from, String to) {
// wrong cipher, return unencrypted string
if (from.length() != to.length()) return text;
// IntStream over the codepoints of this text string
return text.codePoints()
// Stream<Character>
.mapToObj(ch -> (char) ch)
// encrypt characters
.map(ch -> {
// index of this character
int i = from.indexOf(ch);
// if not present, then leave it as it is,
// otherwise replace this character
return i < 0 ? ch : to.charAt(i);
}) // Stream<String>
.map(String::valueOf)
// concatenate into a single string
.collect(Collectors.joining());
}
See also: Implementation of the Caesar cipher

Replacing all characters in a string at once in a for loop

I am learning Java and I have the following method that changes a specific letter in a string:
replaceLetter("The quick brown fox jumps over the lazy dog");
public static void replaceLetter(String string){
string = string.toLowerCase();
for (int i = 0; i < string.length(); i++){
if (string.charAt(i) == 'o'){
// System.out.println("inside if " + i);
// System.out.println("Char at " + string.charAt(i));
System.out.println(string.replace(string.charAt(i), '*'));
break;
}
// System.out.println("Outside if " + i);
}
}
What I don't understand is why is changing all the letters "o" at once, and not one by one as I thought it was supposed to do. The loop loops 12 times outside the "if statement", then goes inside the statement and changes all the characters the matches the case "o". Since the condition is "string.charAt(i)", shouldn't it change one by one? Shouldn't it change the first character that matches the case then break out of the loop?
Because that is what String#replace(char, char) does.
From the Javadoc:
Returns a new string resulting from replacing all occurrences of
oldChar in this string with newChar.
If you want to only replace one character at a time, use String#replaceFirst(char, char)
To quote the javadoc for replace, it (emphasis mine):
Replaces each substring of this string that matches the literal target sequence with the specified literal replacement sequence.
It sounds like you're looking for replaceFirst to replace a single occurrence of a character at a time.
You can use setCharAt of the StringBuilder, so your snippet will look like:
public static String replaceLetter(String string){
StringBuilder stringBuilder = new StringBuilder(string.toLowerCase());
for (int i = 0; i < stringBuilder.length(); i++){
if (stringBuilder.charAt(i) == 'o'){
stringBuilder.setCharAt(i, '*');
break;
}
}
return stringBuilder.toString();
}
Also, String are immutable in Java. You need to create a new string with the character replaced.
string.replace(char a, char b) replaces all the occurrences of char a in string with char b. So you may want to use string.replaceFirst instead.

Java: Replace a specific character with a substring in a string at index

I am struggling with how to actually do this. Say I have this string
"This Str1ng i5 fun"
I want to replace the '1' with "One" and the 5 with "Five"
"This StrOneng iFive fun"
I have tried to loop thorough the string and manually replace them, but the count is off. I have also tried to use lists, arrays, stringbuilder, etc. but I cannot get it to work:
char[] stringAsCharArray = inputString.toCharArray();
ArrayList<Character> charArraylist = new ArrayList<Character>();
for(char character: stringAsCharArray) {
charArraylist.add(character);
}
int counter = startPosition;
while(counter < endPosition) {
char temp = charArraylist.get(counter);
String tempString = Character.toString(temp);
if(Character.isDigit(temp)){
char[] tempChars = digits.getDigitString(Integer.parseInt(tempString)).toCharArray(); //convert to number
charArraylist.remove(counter);
int addCounter = counter;
for(char character: tempChars) {
charArraylist.add(addCounter, character);
addCounter++;
}
counter += tempChars.length;
endPosition += tempChars.length;
}
counter++;
}
I feel like there has to be a simple way to replace a single character at a string with a substring, without having to do all this iterating. Am I wrong here?
String[][] arr = {{"1", "one"},
{"5", "five"}};
String str = "String5";
for(String[] a: arr) {
str = str.replace(a[0], a[1]);
}
System.out.println(str);
This would help you to replace multiple words with different text.
Alternatively you could use chained replace for doing this, eg :
str.replace(1, "One").replace(5, "five");
Check this much better approach : Java Replacing multiple different substring in a string at once (or in the most efficient way)
You can do
string = string.replace("1", "one");
Don't use replaceAll, because that replaces based on regular expression matches (so that you have to be careful about special characters in the pattern, not a problem here).
Despite the name, replace also replaces all occurrences.
Since Strings are immutable, be sure to assign the result value somewhere.
Try the below:
string = string.replace("1", "one");
string = string.replace("5", "five");
.replace replaces all occurences of the given string with the specified string, and is quite useful.

Remove a specific word from a string

I'm trying to remove a specific word from a certain string using the function replace() or replaceAll() but these remove all the occurrences of this word even if it's part of another word!
Example:
String content = "is not like is, but mistakes are common";
content = content.replace("is", "");
output: "not like , but mtakes are common"
desired output: "not like , but mistakes are common"
How can I substitute only whole words from a string?
What the heck,
String regex = "\\s*\\bis\\b\\s*";
content = content.replaceAll(regex, "");
Remember you need to use replaceAll(...) to use regular expressions, not replace(...)
\\b gives you the word boundaries
\\s* sops up any white space on either side of the word being removed (if you want to remove this too).
content = content.replaceAll("\\Wis\\W|^is\\W|\\Wis$", "");
You can try replacing " is " by " ". The is with a space before and one after, replaced by a single space.
Update:
To make it work for the first "is" in the sentence, also do another replace of "is " for "". Replacing the first is and the first space, with an empty string.
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
String input = s.nextLine();
char c = s.next().charAt(0);
System.out.println(removeAllOccurrencesOfChar(input, c));
}
public static String removeAllOccurrencesOfChar(String input, char c) {
String r = "";
for (int i = 0; i < input.length(); i ++) {
if (input.charAt(i) != c) r += input.charAt(i);
}
return r;
}
}

Categories