• 14
• 12
• 9
• 10
• 13

# Editing strings

This topic is 4400 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am trying to create a few commands for my console app when I ran into the problem about editing the command to do specific functions on user input. For example, I have a "-say" and a "-do" command. the say command would make the console output whatever string I input after "-say"(for example, "-say Hello World!"). The problem I ran into is stripping the string if the command whenever it's needed. One solution I tried was using a normal string (char str[];) then doing str += 5; to remove the first 5 characters. That way doesn't work all the time though, so if i typed in the console, -shu hello world!, the command would still think I said -say hello world. In general, what I need is a way to remove a string from the input(the string being "-say " or "-do "(with the space included)). Thanks

##### Share on other sites
So, I understand you are using C.

Step 2: remove the first 5 characters and display (you already did that).
Step 1: check that the four first characters are '-', 's', 'a' and 'y'.

##### Share on other sites
Quote:
 In general, what I need is a way to remove a string from the input(the string being "-say " or "-do "(with the space included)).

Is the string always at the start of the string, also is it guarenteed that the string is only one time in the input?

If it's always at the start you can do something like this (basically what ToohrVyk said, just in a function):
bool is_equal_fixed(char* str1,char* str2,size_t len){    assert( strlen(str1) &gt;= len );    assert( strlen(str2) &gt;= len );    for( int i = 0;i&lt;len;++i)    {        if( str1 != str2 )            return false;    }    return true;}bool starts_with(char* input,char* command){    // is size_t a C type?    size_t cmd_length = strlen(command);     // Make sure input is longer than the command.    assert(cmd_length &lt;= strlen(input) );        return is_equal_fixed(input,command,cmd_length);}

EDIT: If I understand your description right, then you do something like the following:
char str[255]; // Input cant be longer than 255get_input(str);char* out = 0;if( starts_with_say(str ) ){    out = (str+5);}

If that is basically what you are doing then you can run into a problem if str is deleted before we are done using out.

##### Share on other sites
This is a simple proble with a really simple solution, lets not try to over complicate it fellas.

This works just fine
if (str == strstr(str, "-say")){    printf("%s\n", (str+5));}

##### Share on other sites
Actually, I realized me and Thetan made a mistake and forgot to include the fifth character (space) in the checking.

if (str == strstr(str, "-say ")){    printf("%s\n", (str+5));}