Read the file row and split the strings in the row: C/C ++ and python implementation

Source: Internet
Author: User
Tags strtok

I. Problem Description

Given a file, read the strings of each row in the file in sequence (strings are separated by spaces).

For example, the test.txt file contains the following content:

First second third forth (first line)

Th sixth seventh (second top)

... (Other rows)

The read content is: first second third forth second th sixth seventh

Ii. Problem Solving steps

(1) first read all lines of the file

(2) then read each string in sequence for each line

(3) Finally, the read strings are stored in the memory in sequence.

Iii. Programming implementation

1. C language implementation

In C, there is a function:Strtok ()Used to split a string. Its prototype is as follows:

#include <string.h>char* strtok(char str[], const char* delim);

Description:

I,Parameters: Str is the string to be split, and delim is the separator string.

II,Usage: The use of this function is quite strange. If the delimiter character in the str string is found in the delim parameter, the character is changed to '\ 0' (string Terminator ). In the first call, strtok () must be given the str string parameter. In the next call, it must be set to NULL. If each call is successful, the pointer to the split part is returned.

Example:

#include <stdio.h>#include <string.h>int main(){char s[] ="ab|cdef;ghi|jkl";char* delim = "|;";char* tmp;tmp = strtok(s, delim);while(tmp != NULL){printf("%s\n",tmp);tmp = strtok(NULL, delim);}return 0;}

Output:

The following describes the strings in each row of the read file and saves them to the memory. Set the file name to test.txt. The content is as follows:

Corresponding programIs:

# Include <stdio. h> # include <string. h>/* @ in, str: string to be split @ in, delim: separator string @ in_out, dest: Save each string after split and set it to char ** reference, that is, you can modify the value @ out, pCount: record the number of strings split in a row */void split (char * str, char * delim, char ** & dest, int * pCount) {char * tmp; * pCount = 0; if (NULL = str | 0 = strlen (str) return; if (NULL = delim | 0 = strlen (delim) return; tmp = strtok (str, delim); while (tmp! = NULL) {for (int j = 0; tmp [j]! = '\ 0'; j ++) {if (tmp [j] =' \ n') break; // reach the end of a row (* dest) [j] = tmp [j];} (* dest) [j] = '\ 0'; dest ++; (* pCount) ++; tmp = strtok (NULL, delim) ;}} int main () {FILE * fp; char lineBuf [129]; char * delim = ""; // The separator is: Space int num = 0; // The total number of strings in the file int count = 0; // The number of strings in a row int I; /* applied memory is used to store strings */char ** dest = new char * [128]; for (I = 0; I <128; I ++) {dest [I] = new char [64];} char ** tmpDest = dest; if (fp = fopen ("test.txt", "r") {while (fgets (LineBuf, 128, fp )! = NULL) {split (lineBuf, delim, tmpDest, & count); num = num + count ;}} fclose (fp); for (I = 0; I <num; I ++) {printf ("% s \ n", dest [I]);}/* release memory */for (I = 0; I <128; I ++) {delete [] dest [I];} delete [] dest; return 0 ;}

2. c ++ language implementation

C ++ does not implement the split function. Below we use some functions in C ++ STL to simulate the split function.

# Include <iostream> # include <string> # include <vector> # include <fstream> using namespace std;/* @ in, src: string to be split @ in, delim: separator string @ in_out, dest: Save each split string */void split (const string & src, const string & delim, vector <string> & dest) {string str = src; string: size_type start = 0, index; string substr; index = str. find_first_of (delim, start); // in str, locate the first occurrence location of any character of delim (start: start) while (index! = String: npos) {substr = str. substr (start, index-start); dest. push_back (substr); start = str. find_first_not_of (delim, index); // locate the first character that does not belong to delim in str (start: index) if (start = string: npos) return; index = str. find_first_of (delim, start) ;}} int main () {ifstream infile ("test.txt", ios: in); vector <string> results; string word; string delim (""); string textline; if (infile. good () {while (! Infile. fail () {getline (infile, textline); split (textline, delim, results) ;}} infile. close (); vector <string >:: iterator iter = results. begin (); while (iter! = Results. end () {cout <* iter ++ <endl;} return 0 ;}

3. Python implementation

There are special functions in PythonSplit ()Splits strings to simplify implementation

Myfile = open('test.txt ', 'R') allwords = [] line = myfile. readline () while line: List = line. split ('') for word in list: If word [-1] = '\ N': allwords. append (word [:-1]) # Remove '\ n' else: allwords at the end of the row. append (Word) line = myfile. readline () myfile. close () print allwords

References:

1. Implement split string in C/C ++-Russell lab

2. strtok functions-Baidu encyclopedia

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.