Hi,
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.

Thanks,
oling

Recommended Answers

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 developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.