A Better Way to Split a String into an Array of Strings in C/C++ Using Whitespace as a Delimiter

C - split string into an array of strings

Since you've already looked into strtok just continue down the same path and split your string using space (' ') as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp.

See the below example, but keep in mind that strtok will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy or similar function.

char    str[]= "ls -l";
char ** res = NULL;
char * p = strtok (str, " ");
int n_spaces = 0, i;

/* split string and append tokens to 'res' */

while (p) {
res = realloc (res, sizeof (char*) * ++n_spaces);

if (res == NULL)
exit (-1); /* memory allocation failed */

res[n_spaces-1] = p;

p = strtok (NULL, " ");
}

/* realloc one extra element for the last NULL */

res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;

/* print the result */

for (i = 0; i < (n_spaces+1); ++i)
printf ("res[%d] = %s\n", i, res[i]);

/* free the memory allocated */

free (res);

res[0] = ls
res[1] = -l
res[2] = (null)

how to split a string using space delimiter in C unix?

Your problem can be split into two parts, part A you need to split the sentence into words and part B you need to print a maximum of x characters per line.

Part A - Split the String

Take a look at the strok function. You can use space as the delimiter.

#include <stdio.h>
#include <string.h>
// You need this line if you use Visual Studio
#pragma warning(disable : 4996)

int main()
{
char myString[] = "the quick brown fox";
char* newString;
newString= strtok(myString, " ,.-");
while (newString!= NULL)
{
printf("%s\n", newString);
newString= strtok(NULL, " ,.-");
}

return 0;
}

Output:

the
quick
brown
fox

Part B

Now you want to print the words and insert a newline when you reach the max columns 12 in your example.
You need to check the length of every extracted word, you can use strlen for that.
When the string is to long you insert a newline...

Hope it helped, if something is unclear leave a comment.

splitting a string into an array in C++ without using vector

It is possible to turn the string into a stream by using the std::stringstream class (its constructor takes a string as parameter). Once it's built, you can use the >> operator on it (like on regular file based streams), which will extract, or tokenize word from it:

#include <iostream>
#include <sstream>

using namespace std;

int main(){
string line = "test one two three.";
string arr[4];
int i = 0;
stringstream ssin(line);
while (ssin.good() && i < 4){
ssin >> arr[i];
++i;
}
for(i = 0; i < 4; i++){
cout << arr[i] << endl;
}
}

Is it possible to split a string into an array of strings and remove sections not between delimiters using String.Split or regex?

Making the assumption that commas are not permitted inside a curly brace pair, and that outside a curly brace pair only commas or whitespace will appear, it seems to me that the most straightforward, easy-to-read way to approach this is to first split on commas, then trim the results of that (to remove whitespace), and then finally to remove the first and last characters (which at that point should only be the curly braces):

valuesCombined.Split(',').Select(s => s.Trim().Substring(1, s.Length - 2)).ToArray();

I believe that including the curly braces in the initial split operation just makes everything harder, and is more likely to break in hard-to-identify ways (i.e. bad data will result in weirder results than if you use something like the above).

Split string in C every white space

http://www.cplusplus.com/reference/clibrary/cstring/strtok/

Take a look at this, and use whitespace characters as the delimiter. If you need more hints let me know.

From the website:

char * strtok ( char * str, const char * delimiters );

On a first call, the function expects a C string as argument for str, whose first character is used as the starting location to scan for tokens. In subsequent calls, the function expects a null pointer and uses the position right after the end of last token as the new starting location for scanning.

Once the terminating null character of str is found in a call to strtok, all subsequent calls to this function (with a null pointer as the first argument) return a null pointer.

Parameters


  • str

    • C string to truncate.
    • Notice that this string is modified by being broken into smaller strings (tokens).
      Alternativelly [sic], a null pointer may be specified, in which case the function continues scanning where a previous successful call to the function ended.
  • delimiters

    • C string containing the delimiter characters.
    • These may vary from one call to another.

Return Value


A pointer to the last token found in string.
A null pointer is returned if there are no tokens left to retrieve.

Example

/* strtok example */
#include <stdio.h>
#include <string.h>

int main ()
{
char str[] ="- This, a sample string.";
char * pch;
printf ("Splitting string \"%s\" into tokens:\n",str);
pch = strtok (str," ,.-");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, " ,.-");
}
return 0;
}

How to split a String by space

What you have should work. If, however, the spaces provided are defaulting to... something else? You can use the whitespace regex:

str = "Hello I'm your String";
String[] splited = str.split("\\s+");

This will cause any number of consecutive spaces to split your string into tokens.

Parse (split) a string in C++ using string delimiter (standard C++)

You can use the std::string::find() function to find the position of your string delimiter, then use std::string::substr() to get a token.

Example:

std::string s = "scott>=tiger";
std::string delimiter = ">=";
std::string token = s.substr(0, s.find(delimiter)); // token is "scott"
  • The find(const string& str, size_t pos = 0) function returns the position of the first occurrence of str in the string, or npos if the string is not found.

  • The substr(size_t pos = 0, size_t n = npos) function returns a substring of the object, starting at position pos and of length npos.


If you have multiple delimiters, after you have extracted one token, you can remove it (delimiter included) to proceed with subsequent extractions (if you want to preserve the original string, just use s = s.substr(pos + delimiter.length());):

s.erase(0, s.find(delimiter) + delimiter.length());

This way you can easily loop to get each token.

Complete Example

std::string s = "scott>=tiger>=mushroom";
std::string delimiter = ">=";

size_t pos = 0;
std::string token;
while ((pos = s.find(delimiter)) != std::string::npos) {
token = s.substr(0, pos);
std::cout << token << std::endl;
s.erase(0, pos + delimiter.length());
}
std::cout << s << std::endl;

Output:

scott
tiger
mushroom

JavaScript split String with white space

You could split the string on the whitespace and then re-add it, since you know its in between every one of the entries.

var string = "text to split";
string = string.split(" ");
var stringArray = new Array();
for(var i =0; i < string.length; i++){
stringArray.push(string[i]);
if(i != string.length-1){
stringArray.push(" ");
}
}

Convert string array to strings with a whitespace separating them

You can use this code to get String with whitespace.

String[] array = {"a", "b", "c"};
String output = "";
for (int i = 0; i < array.length; i++) {
output += array[i] + " ";
}


Related Topics



Leave a reply



Submit