How to replace multiple consecutive question marks (?) with a single question mark in C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>

void replaceMultipleQuestionMarks(char *str) {
    int i = 0, j = 0;
    int len = strlen(str);
    char result[len + 1]; // Temporary array to store the result

    while (str[i] != '\0') {
        result[j++] = str[i];
        if (str[i] == '?') {
            while (str[i] == '?') {
                i++; // Skip consecutive question marks
            }
        } else {
            i++;
        }
    }
    result[j] = '\0'; // Null-terminate the result string
    strcpy(str, result); // Copy the result back to the original string
}

int main() {
    char str[] = "Hello??? How are you?? What is your Wi-Fi password????";

    replaceMultipleQuestionMarks(str);
    
    printf("%s\n", str);
    
    return 0;
}



/*
run:

Hello? How are you? What is your Wi-Fi password?

*/

 



answered Jul 24, 2025 by avibootz
...