Easiest way to replace all characters in even positions in a string.
It is easily done with a regular expression:
echo preg_replace('/(.)./', '$1 ', $str);
The dot matches a character. Every second character is replaced with a space.
How to replace even values in string with ASCII value?
You are almost there, you simply need to build the resulting string.String
s are immutable, so replacing would create a new String each time.
I would suggest a StringBuilder
for this task, but you can also do it manually.
The result would look like this:
public static void main(String[] args) {
String str = "ABCDEF";
StringBuilder sb = new StringBuilder();
for (int i = 0; i < str.length(); i++) {
if (i % 2 != 0) {
int m = str.charAt(i);
sb.append(m); // add the ascii value to the string
} else {
sb.append(str.charAt(i)); // add the normal character
}
}
System.out.println(sb.toString());
}
Output:
A66C68E70
How to replace odd/even chars in string with spaces in Java?
You could simply split the input on the space and process each work individually. You could then use a StringJoiner
to piece together the result, for example...
String s = "go to med!!";
String alphabetS = "abcdefghijklmnopqrstuvwxyz";
String[] words = s.split(" ");
StringJoiner sj = new StringJoiner(" ");
for (String word : words) {
StringBuilder sb = new StringBuilder(word);
for (int i = 0; i < sb.length(); i++) {
char currChar = sb.charAt(i);
int idx = alphabetS.indexOf(currChar);
if (idx != -1) {
if (i % 2 == 1) {
sb.setCharAt(i, '*');
}
}
}
sj.add(sb.toString());
}
System.out.println(sj.toString());
which outputs
g* t* m*d!!
could this be done without using arrays - just with char and string methods?
Instead of relying on i
, you need a separate counter, which tracks which point your up to and which can be used to ignore invalid characters, for example
String s = "go to med!!";
String alphabetS = "abcdefghijklmnopqrstuvwxyz";
StringBuilder sb = new StringBuilder(s);
int counter = 0;
for (int i = 0; i < sb.length(); i++) {
char currChar = sb.charAt(i);
int idx = alphabetS.indexOf(currChar);
if (idx != -1) {
if (counter % 2 == 1) {
System.out.println("!!");
sb.setCharAt(i, '*');
}
counter++;
}
}
System.out.println(sb.toString());
which still outputs
g* t* m*d!!
String builder replace elements at even indexes in string
Some things I will correct, but @Nikolai Dmitriev already pointed some of them out.
- The
n
is needed, even though @Nikolai Dmitriev said it's not. Since you want to replace it with its ASCII value. However, you can shorten it toString a = String.valueOf((int) c);
or even get rid of thec
and just straight up use `String a = String.valueOf((int) sb.charAt(i)); - You are using
sb.replace(char start, char end, String str);
while the function should acceptsb.replace(int start, int end, String str);
. To correct this, just usesb.replace(i, i + 1, a);
. Notice that you useend = i + 1
because the StringBuilder replace function end value is exclusive (not including). - Initialize
result
at the end. The variable has a scope of inside the for loop if you do it inside, and since you want to return it, you would want to initialized it after you finish replacing all even-indices.
How to replace characters in a string in python
name = "ABCDEFGH"
nameL = list(name)
for i in range(len(nameL)):
if i%2==1:
nameL[i] = '$'
name = ''.join(nameL)
print(name)
How would I remove letters at an even position throughout a string in Java?
Try this.
- It uses a regex that takes two chars at a time and replaces them with the 2nd, thus removing every other one.
- the
(.)
is a capture group of 1 character. $1
is a back reference to it.
String s = "abcdefghijklmnopqrstuvwxyz";
s = s.replaceAll("(?s).(.)?", "$1");
System.out.println(s);
Prints
bdfhjlnprtvxz
per Andreas suggestion, I preceded the regex with a flag that lets .
match returns and linefeeds.
Related Topics
How to Set Current Date as Default Value of an Input
Laravel 5.5 Error 500 in Cpanel Shared Hosting
Dynamically Display a CSV File as an HTML Table on a Web Page
Windows 10 Docker:/Usr/Bin/Env: 'Php\R': No Such File or Directory
How to Insert Special Character in MySQL Via PHP and Display on HTML Page
How to Expire a PHP Session After 30 Minutes
How to Configure Xampp to Send Mail from Localhost
Are Global Variables in PHP Considered Bad Practice? If So, Why
Php Passing Variable Id Through Href
Regex: Number Range Excluding Specific Number
How to Get the Domain Name Without Www, Subdomain, and Com/Net/Org/Etc
How to Get Toggle Button Working With PHP
Display Data from Database to Dropdown Codeigniter
404 Not Found; Apache Server Can't Load Simple PHP File