Home > Net >  How to split a string and store in different variables of a structure?
How to split a string and store in different variables of a structure?

Time:11-20

I have a string " IN1::1209 OUT1::677 CURR1::4 KWh1::3 " so i need only the values and that values to be stored in a structure. basically what I mean is that ex: IN::1209 here I want only 1209 value and that value to be stored in a structure variable.

CodePudding user response:

In C, the strtok() function is used to split a string into a series of tokens based on a particular delimiter. A token is a substring extracted from the original string.

The general syntax for the strtok() function is:

char *strtok(char *str, const char *delim)

Example:

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

int main() {
   char string[50] = "Hello! We are learning about strtok";
   // Extract the first token
   char * token = strtok(string, " ");
   // loop through the string to extract all other tokens
   while( token != NULL ) {
      printf( " %s\n", token ); //printing each token
      token = strtok(NULL, " ");
   }
   return 0;
}

ouput:

Hello!
 We
 are
 learning
 about
 strtok

Refer this link for more.

CodePudding user response:

Here is a function that receives by reference a string, which is the parameter you want to split (in my case was a key-value string) and another string, which is the delimiter parameter.

It returns the two (separated by delimiter) parts of the first string parameter (line) in a std::pair.

std::pair<std::string, std::string> split_key_value_pair( const std::string & line, const std::string & delimiter ){
    
    std::size_t pos = line.find( delimiter );

    std::pair<std::string, std::string> key_value;
    key_value.first = line.substr(0, pos);
    key_value.second = line.substr(pos   delimiter.size());

    return key_value;
}

Basically, after splitting the text that you want by the delimiter parameter, you can get the part of importance, first or second.

Example

/*create input */
    std::string my_text = "IN::1209";
    std::string delimiter = "::";

    
/* call routine */
    std::pair<std::string, std::string> key_value = split_key_value_pair(my_text, delimiter);
    

/* print to screen the output */
    std::cout << key_value.first() << std::endl; //will print IN
    std::cout << key_value.second() << std::endl; //will print 1209
  •  Tags:  
  • c
  • Related