Separating a single string into two different strings in C [duplicate] - c

This question already has answers here:
Split string with delimiters in C
(25 answers)
Closed 9 years ago.
I take user input in char name[20] using fgets like this:
fgets(name,20,stdin);
The user enters two strings separated by white space like John Smith. What if I wanted to use John and Smith in two strings like char name[20] , char surname[20] or just compare John and Smith using strcmp?
I tried a lot, but I did not find any way to do this.
What are some ways to fix this kind of problem?

You need to learn char * strtok (char *restrict newstring, const char *restrict delimiters) function in C uses to splitting a string up into token separated by set of delimiters.
You input string John Smith is separated by space (' ') char. You need to write a code something like below:
char *token;
token = strtok(name, " "); // first name
strcpy(fname, token);
token = strtok(NULL, " "); // second name
strcpy(lname, token);

You will need to search for the blank within the string yourself - look up the strchr function for that. Then, use strncpy to copy the two parts in 2 different strings.

Use the strtok function to split strings.

Related

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

This question already has answers here:
C function for separate a string in array of chars
(5 answers)
Closed 5 years ago.
I am new in C programming, my training uses Redhat, Unix and I already spent my day searching for a solution. I know manipulating a string in C is difficult for me as beginner.
How can I split the string into individual words so I can loop through them?. Or convert a string into char array to be able to access individual elements.
char myString[] = "the quick brown fox";
To be exact i want to print each word of the said string into a fixed column and whenever the the string reached that number of column it will go to new line and print the sequence without splitting the word.
eg. print it within 12 columns only w/out splitting the word:
the quick
brown fox
and not:
the quick br
own fox
..TIA
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.

C strtok, split string to two part using first space

i have 3 pointers
char line[MAX_STR];
char *inputCmd,*inputArgs;
and i'm using
inputCmd = strtok(line," ");
I wonder how i can split it to just two parts
In example
line = {"COMMAND A PARAMTER TO CHECK..."};
I want the
inputCmd will point to "COMMAND"
and inputArgs will point to "A PARAMTER TO CHECK..."
Thanks.
I
You don't have to use the same token for every call to strok.
So if your format is
string1|space|remainder|nul|
you can call strtok with a space and the string, then call again with null for the string argument and nul for the token.

Mystery about strtok() function [duplicate]

This question already has answers here:
How does strtok() split the string into tokens in C?
(16 answers)
Closed 6 years ago.
Sorry for probably a stupid question but, after reading a considerably amount of examples I still don't understand how strtok() works.
Here is example:
char s[] = " 1 2 3"; // 3 spaces before 1
int count = 0;
char* token = strtok(s, " ");
while (token != NULL) {
count++;
token = strtok(NULL, " ");
}
After executing count equals 3. Why?
Please explain I've given detailed steps of what happens inside the call to that function.
Because:
http://man7.org/linux/man-pages/man3/strtok.3.html
From the above description, it follows that a sequence of two or more
contiguous delimiter bytes in the parsed string is considered to be a
single delimiter, and that delimiter bytes at the start or end of the
string are ignored.
You could also have print the consecutive tokens.
Output for me:
1
2
3
It is C, but C++ reference has a nice example: http://www.cplusplus.com/reference/cstring/strtok/
char s[] once initialized, points to a memory location with data: 1 2 3.
First call to strtok, with delimiter a single space, advances the pointer to point to further memory loaction, now with just: 1 2 3. Further calls increase the pointer, to point to locations of consecutive tokens.
Note: think of strtok() as a tokenizer function, iterating forward by the valid tokens. Also, printing out the current value of pch may help to understand it better (or use a debugger).

Find words divided by whitespace

Is it possible to use fgets() to save different words divided by whitespace and then find each word?
For example let's say I have this:
char words[100];
fgets(words,100,stdin);
and then I have to find each word to use it in the rest of my program. How can I do that?
You can use strtok_r or you could use the pcre library if you want to do things with regex.
char *save_ptr;
char *word = strtok_r(words, " \t", save_ptr);
and then repeated other calls to
word = strtok_r(words, " \t", save_ptr);
until word == NULL
fgets() will save your input into a string. To divide it into individual words, you can either go through the string (possibly using isalpha() and similar), or use strtok() to get individual words.

Can scanf identify a format character within a string?

Let's say that I expect a list of items from the standard input which are separated buy commas, like this:
item1, item2, item3,...,itemn
and I also want to permit the user to emit white-spaces between items and commas, so this kind of input is legal in my program:
item1,item2,item3,...,itemn
If I use scanf like this:
scanf("%s,%s,%s,%s,...,%s", s1, s2, s3, s4,...,sn);
it will fail when there are no white-spaces (I tested it) because it will refer to the whole input as one string. So how can I solve this problem only with C standard library functions?
The quick answer is never, ever use scanf to read user input. It is intended for reading strictly formatted input from files, and even then isn't much good. At the least, you should be reading entire lines and then parsing them with sscanf(), which gives you some chance to correct errors. at best you should be writing your own parsing functions
If you are actually using C++, investigate the use of the c++ string and stream classes, which are much more powerful and safe.
You could have a look at strtok. First read the line into a buffer, then tokenize:
const int BUFFERSIZE = 32768;
char buffer[BUFFERSIZE];
fgets(buffer, sizeof(buffer), stdin);
const char* delimiters = " ,\n";
char* p = strtok(buffer, delimiters);
while (p != NULL)
{
printf("%s\n", pch);
p = strtok(NULL, delimiters);
}
However, with strtok you'll need to be aware of the potential issues related to reentrance.
I guess it is better to write your own parsing function for this. But if you still prefer scanf despite of its pitfalls, you can do some workaround, just substitute %s with %[^, \t\r\n].
The problem that %s match sequence of non white space characters, so it swallows comma too. So if you replace %s with %[^, \t\r\n] it will work almost the same (difference is that %s uses isspace(3) to match space characters but in this case you explicitly specify which space characters to match and this list probably not the same as for isspace).
Please note, if you want to allow spaces before and after comma you must add white space to your format string. Format string "%[^, \t\r\n] , %[^, \t\r\n]" matches strings like "hello,world", "hello, world", "hello , world".

Resources