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 () is used to split a string. Its prototype is as follows:


[Cpp] view plaincopyprint?
# Include <string. h>
Char * strtok (char str [], const char * delim );

# Include <string. h>
Char * strtok (char str [], const char * delim );
Note:

I. Parameter: 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:


[Cpp]
# 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;
}

# 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:

 



The corresponding program is:


[Cpp]
# Include <stdio. h>
# Include <string. h>
 
/*
@ In, str: string to be split
@ In, delim: delimiter string
@ In_out, dest: saves each split string and sets it as a reference of char **, which indicates that the value can be modified.
@ Out, pCount: record the number of strings split in one 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; // arrives at the end of the row
(* Dest) [j] = tmp [j];
}
(* Dest) [j] = '\ 0 ';
Dest ++;
(* PCount) ++;
 
Tmp = strtok (NULL, delim );
}
}
Int main ()
{
 
FILE * fp;
Char lineBuf [129];
Char * delim = ""; // delimiter: Space
Int num = 0; // The total number of strings in the file
Int count = 0; // The number of strings in a row
Int I;
 
/* Memory 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 the memory */
For (I = 0; I <128; I ++)
{
Delete [] dest [I];
}
Delete [] dest;
 
Return 0;
}

# Include <stdio. h>
# Include <string. h>

/*
@ In, str: string to be split
@ In, delim: delimiter string
@ In_out, dest: saves each split string and sets it as a reference of char **, which indicates that the value can be modified.
@ Out, pCount: record the number of strings split in one 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; // arrives at the end of the row
(* Dest) [j] = tmp [j];
}
(* Dest) [j] = '\ 0 ';
Dest ++;
(* PCount) ++;

Tmp = strtok (NULL, delim );
}
}
Int main ()
{

FILE * fp;
Char lineBuf [129];
Char * delim = ""; // delimiter: Space
Int num = 0; // The total number of strings in the file
Int count = 0; // The number of strings in a row
Int I;

/* Memory 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 the 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.


[Cpp]
# Include <iostream>
# Include <string>
# Include <vector>
# Include <fstream>
Using namespace std;
 
/*
@ In, src: string to be split
@ In, delim: delimiter 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); // locate the first occurrence location of any character of delim in str (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 position where the first character that does not belong to delim appears 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;
}

# Include <iostream>
# Include <string>
# Include <vector>
# Include <fstream>
Using namespace std;

/*
@ In, src: string to be split
@ In, delim: delimiter 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); // locate the first occurrence location of any character of delim in str (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 position where the first character that does not belong to delim appears 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

In Python, there is a special function split () to separate strings, which is easier to implement.


[Python]
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' at the end of the row'
Else:
AllWords. append (word)
Line = myfile. readline ()
Myfile. close ()
Print allWords

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' at the end of the row'
Else:
AllWords. append (word)
Line = myfile. readline ()
Myfile. close ()
Print allWords

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.