简体   繁体   中英

Get a string and extract 2 substring in c

I just want to read from input a string of the form "c4 d5" and save two substring :

str1 = "c4"

str2 = "d5"

I tried:

char action[5];
char str1[2];
char str2[2];
scanf("%s", action);
strncpy(str1, &action[0], 2);
strncpy(str2, &action[3], 2);

but it gives me strange behaviors....

Also as I am learning c, I'm looking for both solutions using only char * and only char[] (either in input and output).

When you expire strange behaviour ALWAYS read the man pages of the functions you are using. AC string should with almost no exceptions end with a \\0 because otherwise printf/puts will probably not only print what you want but also some random memory fragments. Also the index starts at 0 so in order to get the third char you need to use [2].

#include <stdio.h>

int main()
{
    char action[5];
    char str1[3];
    char str2[3];

    scanf("%s", action);

    strncpy(str1, action, 2);
    strncpy(str2, &action[2], 2);

    str1[2] = '\0';
    str2[2] = '\0';

    puts(str1);
    puts(str2);

    return 0;
}

Try it out

man page of strncpy

The strncpy() function is similar, except that at most n bytes of src are copied. Warning: If there is no null byte among the first n bytes of src, the string placed in dest will not be null-terminated.

Here is a substring function. Don't forget to free the result when needed.

/**
 * Substrings in a new string, handles \0
 * @param char* str , the string to substring
 * @param int from , the start index included
 * @param int count , the amount of characters kept
 */
char * strsubstr(char * str , int from, int count) {
    char * result;

    if(str == NULL) return NULL;

    result = malloc((count+1) * sizeof(char));

    if(result == NULL) return NULL;

    strncpy(result, str+from, count);
    result[count] = '\0';
    return result;
}

At first you must understand some basic principles of c.
Scanf stops its %s "string-reader" if it's read a space
secondly you can read both of the strings in once. "%s %s"
at this case you do not need the action variable:

#include <stdio.h>
#include <string.h>
int main(int argc, char const *argv[])
{
    char str1[2];
    char str2[2];
    scanf("%s %s",str1,str2);
    return 0;
}

This way you take cover of the space termination and the pointers game..

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