Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a file lines with space and tab differentiation? [duplicate]

I have a file in below format

mon 01/01/1000(TAB)hi hello(TAB)how r you

Is there any way to read the text in such a way to use '\t' alone as delimiter (and not space)?

So sample output can be,

mon 01/01/1000

hi hello

how r you

I couldn't use fscanf(), since it reads till the first space only.

like image 440
John Avatar asked May 16 '12 10:05

John


People also ask

How do you split a line with spaces in Python?

Python String split() MethodThe split() method splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

How do you split a string with spaces?

To split a string with space as delimiter in Java, call split() method on the string object, with space " " passed as argument to the split() method. The method returns a String Array with the splits as elements in the array.

How do you split a string by Tab?

split() method to split a string by tab, e.g. my_list = re. split(r'\t+', my_str) . The re. split() method will split the string on each occurrence of a tab and return a list containing the results.


2 Answers

Using only standard library facilities:

#include <sstream>
#include <fstream>
#include <string>
#include <vector>

std::ifstream file("file.txt");

std::string line;

std::vector<std::string> tokens;

while(std::getline(file, line)) {     // '\n' is the default delimiter

    std::istringstream iss(line);
    std::string token;
    while(std::getline(iss, token, '\t'))   // but we can specify a different one
        tokens.push_back(token);
}

You can get some more ideas here: How do I tokenize a string in C++?

like image 55
jrok Avatar answered Sep 19 '22 02:09

jrok


from boost :

#include <boost/algorithm/string.hpp>
std::vector<std::string> strs;
boost::split(strs, "string to split", boost::is_any_of("\t"));

you can specify any delimiter in there.

like image 23
WeaselFox Avatar answered Sep 23 '22 02:09

WeaselFox