84.7k views
2 votes
In C, how could I use a command line input to remove certain characters from an existing string? For example, if I have string 'OXOXO' and whenever the character 'N' is put into the command line, a character from the existing string would be removed. So if the user inputs the string 'oNoN' into the command line, the new string would be 'OXO'.

1 Answer

1 vote

Answer:

// here is code in C.

#include <stdio.h>

// main function which take input from command line

int main(int argc, char** argv) {

// variables

int char_count = 0, i=0;

// string as char array

char inp_str[100] = "OXOXO";

//count total number of 'N's in command line argument

while(argv[1][i++] != '\0')

{

if(argv[1][i]=='N')

char_count++;

}

// find the length string

int l = 0;

while(inp_str[l] != '\0')

l++;

//reduce length of the string

l = l - char_count;

//set null char at index "l" so it will removes character after index "l"

inp_str[l] = '\0';

printf("%s\\", inp_str);

return 0;

}

Step-by-step explanation:

Create a string as character array and initialize it with "OXOXO".After that count the number of "N" which come from the command line argument.Then find the length of input string.Reduce the length of string and set "null" at index "l" in the string.Then print the string.

Output:

OXO

Command line argument:

In C, how could I use a command line input to remove certain characters from an existing-example-1
User Tobypls
by
5.4k points