I am a programming newby and trying to write a Java code that does the following:

- User inputs a string of choice (this part is ok)
- Program reads every third character of the string and replaces with an X

Any help would be appreciates.


Recommended Answers

Convert the String to an array of characters (look the java String API)
Loop the array and for every third element set its value to X (array = 'X')
Then convert that array of characters to a new String (look the java String API)


Jump to Post

All 3 Replies

This is what I have now. Is still have not figured out how to replace every third character in the input string (I just put in replace all 'a' that appear in the string to make the program work). Can you please help with how to count every third character and replace?

import java.util.Scanner;

public class ReplaceChar
  public static void main (String[] args)
  String str, str_new="";
  int i;
  char ch;
  Scanner scan = new Scanner(System.in);
  str = scan.next();
    for(i = 0; i < str.length()-1; i++) {
      ch = str.charAt(i);
      if(ch == 'a') 
      str_new = str.replace(ch, 'X');
  System.out.println("Original string: \"" + str + "\"");
  System.out.println("New string: \"" + str_new + "\"");

That code has nothing to do with what I suggested. Also why do you loop until length-1 and not length?
Use my suggestions to create an array of characters and loop it. In order to change every third character in the loop have an if statement that checks if that index of the array can be divided by 3. Use the '%' operator:

14%2 = 0
14%7 = 0

3%3 = 0
6%3 = 0
9%3 = 0

If it returns 0 then it can be divided:

int a = 5;
int b = 2;
int mod = a%b;

If the index of the array can be divided then change it with the 'X' as explained in my first post. Then convert that char array to a String. Look at those methods at the String API

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.20 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.