Sabina
Sabina

Reputation: 3

Replace a char at Nth position

The main idea of this code to replace a char at a specific position.When I try to compile this code it gives me nothing, If I cane text2(For example: text2 = "lll" it shows me "lll". If it is possible give me a hint the way to solve my problem. :)

public static void main(String[] args)
{
    String text3 = "Yeaaaaah";
    replaceNth(text3, 1, 'a', 'o');
}

public static String replaceNth(String text, int n, char oldValue, char newValue)
{
    String text2 = "";
    char[] array1 = text.toCharArray();

    for (int i = 0; i < text.length(); i++) {
        if (array1[i] == oldValue) {
            if (i == n) {
                array1[i] = newValue;
                text2 = text.substring(0) + array1[i] + text.substring(i + 1);
            } else {
                break;
            }
        } else {
            break;
        }
        System.out.println(text2);
    }

    return text2;
}

Upvotes: 0

Views: 685

Answers (3)

apajak
apajak

Reputation: 21

From my point of view it is unnecessary to use 'oldValue' as a parameter of your function. Please look at one of the possibility of function which replace single specified character inside given a String:

  1. Create a list of all characters from given String ('word'),
  2. Setting a new value for given 'position',
  3. Create a StringBuilder and join all characters (with changed single char) into String 'result'.

    public static String replaceCharAtSpecificPosition(String word, int   position, char newValue){
    
       List<Character> chars = word.chars()
               .mapToObj(s -> (char)s)
               .collect(Collectors.toList());
    
       chars.set(position, newValue);
    
       StringBuilder result = new StringBuilder();
    
       for(char eachChar: chars){
           result.append(eachChar);
       }
    
       return result.toString();
    }
    

Example of using this solution inside main:

    String word = "Yeeaaahh";

    String changedWord = replaceCharAtSpecificPosition(word, 2, 'Z');

    System.out.println(changedWord);
    //result: YeZaaahh

Upvotes: 0

Luke
Luke

Reputation: 1344

Analyze the program step by step. Start from the for loop. First it checks whether array1[i] is equal to the old value. For the i==0, that is obviously false ('Y' != 'a'). Because it isn't true, it proceeds executing the else block which says: break; That means exit out of the loop and continue executing with the next statement (which would be System.out.println). Boom, nothing happens with the string, and since it was initialized to "" you get empty String back. Think about what would happen if array1[0] == oldChar, but n != 0 (hint: look at the inner if). Solution: remove elses.

The problem says you should replace every n-th occurrence of oldChar, so you should count how many character matches you have matched so far while iterating. Something like:

for(int i=0; i<text.length; i++) {
    if(textChars[i]==oldChar) matches++;
    if(matches % n == 0) textChars[i] = newChar; //will match n, 2n, 3n,...
}
return String.valueOf(textChars);

Upvotes: 0

Tale Words
Tale Words

Reputation: 55

I made this yesterday:

/*
Changes a character in a string with a character that you enter and returns the new string.
int i - character position
char c - new character
String msg - string that you are editing
*/

public class StringRemastered {
    public String setCharAt(int i, char c, String msg){
        char[] msgArray = msg.toCharArray();
        msgArray[i] = (char) c;
        msg = String.valueOf(msgArray);
        return msg;
    }
}

If the input is:

2, 'o', "Yeaaaaah"

The return value will be:

Yeoaaaah

Upvotes: 1

Related Questions