简体   繁体   中英

c how to cut of the first x words of a string?

I have a char array:

char tmp[2048];

I want to cut of the first x words of tmp. I define a word as a sequence of characters that does not include whitespaces. I tried something like this (should cut of the first 3 words):

sscanf(tmp, "%*s %*s %*s %s", tmp);

My problem is, that '%s' stops at the first whitespace it finds. I want the new string to end at the end of the old string, not at the first whitespace.

I'm also open for other suggestions how to cut of the first x words of a string. I define a word as a sequence of characters that doesn't contain whitespaces.

Here's a rough implementation:

const char* TrimWords(const char* input, int nWords)
{
    while (nWords)
    {
        if (!isspace(*input) && isspace(*(input + 1)))
        {
            nWords--;
        }
        input++;
    }
    return input;
}

TrimWords("One Two Three Four Five", 3);
// returns " Four Five" after the first 3 words are trimmed.

Detailed input validation and error checking is left to the OP.
This is just a good starting point.

use strncpy(tmp, n, tmp+m); where m and n are ints

char tmp[20] = "abcdef";

strncpy(tmp, tmp + 3, 2);

for exmaple: code above will result in decdef

You can use strtok to tokenize strings by whitespace. Something similar to this could do what you're trying to achieve:

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

int main(int argc, char *argv[])
{
    // Number of words to trim
    const int numWords = 2;

    char tmp[1024];
    char buffer[1024];
    sprintf(tmp, "this  is a\tsentence.");

    strcpy(buffer, tmp);

    char* token = strtok(buffer, " \t");
    for (int i = 0; i < numWords && token; i++) {
        token = strtok(NULL, " \t");
    }

    if (token) {
        size_t len = 1024 - (token - buffer);
        memmove(tmp, tmp + (token - buffer), len);
    }
    else {
        memset(tmp, '\0', 1024);
    }

    // Prints "a    sentence."
    printf("%s", tmp);
    return 0;
}

However, the use of strtok is tricky at best. I would suggest using an approach similar to that of abelenky's answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM