I want to split a string into two strings in C - c

I want to split a string by the comma and separate the first number in the string into its own new string, the rest of the string I want to keep together.
So far I have tried this by using strtok() and I can get the first number into its own string, but now I can't figure out how to keep the rest of the string together.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
char testStr[] = "1000,first,second,third,+abc";
char *uidStr;
char *restOfstr;
int n;
//This is wrong, I know, but I want to populate
//the rest of the string after the first comma
//into a single string without the UID.
uidStr = strtok(testStr, ",");
while (n < 5)
{
restOfstr = strtok(NULL, ",");
n++;
}
return 0;
}

strtok works fine, you have to keep in mind that it returns a pointer to each tokenized word so you need two pointers one for the first token and other for the rest of the string.
Demo
#include <stdio.h>
#include <string.h>
int main()
{
char testStr[] = "1000,first,second,third,+abc";
char *uidStr; //pointer to uid
char *restOfstr; //pointers to the rest of the string
uidStr = strtok(testStr, ","); //uid remains in testStr
restOfstr = strtok(NULL, "\n"); //rest of the string
puts(uidStr); //or puts(testStr) to print uid
puts(restOfstr); //print rest of the string
return 0;
}
If you want a more secure function you can use strtok_s.

You can use strchr to find the first comma in the string.
Then using strncpy to get the number in the string.
The complete code:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *str = "1000,first,second,third,+abc";
char *s = strchr(str, ',');
if(!s)
return -1;
char num[10];
strncpy(num, str, s-str);
num[s-str] = '\0';
int a = strtol(num, NULL, 10);
printf("num = %d\nthe remaining: %s\n", a, s+1);
return 0;
}

#include <string.h>
#include <stdio.h>
int main(int ac, char **av) {
while (--ac) {
char *p = *++av;
char *t = strtok(p, ",");
char *r = strtok(NULL,"");
printf("%s : %s\n", t, r);
}
return 0;
}
Note that the empty string "" passed to the second strtok means that it cannot find a deliminator, thus returns the rest of the string.

In addition to the excellent answers #mevets and #anastaciu have provided (I would go with these), this code will also work fine.
#include <string.h>
#include <stdio.h>
int main(int argc, char** argv) {
char _p[] = "1000,Hey,There";
char* str1 = strtok(_p, ",");
char* str2 = strtok(NULL, "");
return 0;
}

Related

Segmentation error when convert string to array of strings in c

I want to convert a string to an array of strings and I get an error
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
int count = 0;
char *str = argv[1];
char *token, *last;
char **arr_str = calloc(9999, sizeof(char*));
token = strtok_r(str, " ,", &last);
arr_str[count] = strcpy(calloc(strlen(token), sizeof(char)), token);
while (token != NULL) {
count++;
token = strtok_r(NULL, " ", &last);
arr_str[count] = strcpy(calloc(strlen(token), sizeof(char)), token);
printf("%s", arr_str[count - 1]);
}
printf("------------");
while(arr_str[count])
printf("%s", arr_str[count--]);
exit (0);
}
how to allocate memory for a string and make a pointer to it from an array?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(int argc, char **argv)
{
/* always check argument count */
if(argc < 2) {
printf("Not enough arguments given\n");
return 1;
}
int count = 0;
char *str = malloc(strlen(argv[1] + 5));
memcpy(str, argv[1], strlen(argv[1]));
char *token, *last;
char **arr_str = calloc(9999, sizeof(char*));
token = strtok_r(str, " ,", &last);
while ((token = strtok_r(NULL, " ", &last)) != NULL) {
count++;
/* sizeof(char) is always 1 and is redundant unless you are on
a obscure platform that it returns other than 1
which shouldnt exist in modern world
*/
arr_str[count] = malloc(strlen(token) + 1);
strcpy(arr_str[count], token);
}
printf("------------");
while(arr_str[count])
printf("%s", arr_str[count--]);
exit (0);
}
strtok is destructive meaning it edits strings it encounters, it tried to edit argv which resulted in a segmentation error.
I also edited code to follow better practices and edited formatting.
You need memory for elements of the arr_str.
calloc(9999) while not great if this not going to end up in a serious application it's not a issue.
sizeof(char) should always return 1 on a normal modern system unless you are on extremely obscure system
Use puts(char* s) if you don't need string formatting.
You should do input validation.

C: Strange behaviour with strtok()

I'm doing an exercice where I need to split a string into an array of strings. The number of delimiters is checked before (the code snippet posted is a stripped down version however it doesn't work too), then the string is transformed into lowercase and it gets split into 4 parts separated by the delimiter "-". Here's the code:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
#define MAX_USERNAME_LENGHT 256
#define NUMBER_OF_ELEMENTS 4
void StringToArrayOfStrings(char *string, char **string_array, char *delimiter);
void LowerString(char * string, int string_lenght);
int main() {
char string[MAX_USERNAME_LENGHT] = "Joseph-Lucy-Mike-Nick"; //Test string
char *string_array[NUMBER_OF_ELEMENTS]; //We need four elements
char delimiter[] = "-";
int counter = 0;
//LowerString(string, strlen(string));
//printf("%s", string);
StringToArrayOfStrings(string, string_array, delimiter);
//Print each element of the string array
for (counter = 0; counter < NUMBER_OF_ELEMENTS; counter++) {
printf("\n%s\n", string_array[counter]);
}
return 0;
}
void LowerString(char * string, int string_lenght) {
unsigned short int counter;
for (counter = 0; counter < string_lenght; counter++) {
string[counter] = tolower(string[counter]);
}
}
void StringToArrayOfStrings(char *string, char **string_array, char *delimiter) {
unsigned short int counter;
char *token;
token = strtok(string, delimiter);
while(token != NULL) {
string_array[counter++] = token;
token = strtok(NULL, delimiter);
}
}
I've been scratching my head for the past 2 hours and I wasn't able to fix it. This programs works only if the string is not printed or/and transformed in lowercase. The program crashes when entering the loop in StringToArrayOfStrings. Where's the problem?
Thanks.

strtok in C crashes with char pointer

I have a char array in C with numbers separated by comma, and need to convert it to an int array. However when I try to use strtok, it crashes with EXC_BAD_ACCESS.
Can you help me please?
The method
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ARRAY_LEN (0x100)
#define OUTPUT_LEN (0x400)
unsigned int StaticAnalyze_load( char* data, char delimiter, int* array, unsigned int length ){
char *token;
int i=0;
// CRASHES HERE (BAD ACCESS)
token = strtok(data, &delimiter);
while( token != NULL ) {
array[i] = atoi(token);
token = strtok(NULL, &delimiter);
i++;
}
for(i=0;i<3;i++) {
printf("%d\n", array[i]);
}
return length;
}
Main
int main(int argc, const char * argv[]) {
char *data = "13,654,24,48,1,79,14456,-13,654,13,46,465,0,65,16,54,1,67,4,6,74,165,"
"4,-654,616,51,654,1,654,654,-61,654647,67,13,45,1,54,2,15,15,47,1,54";
int array[ARRAY_LEN]; // array, I need to fill-in with integers from the string above
unsigned int loaded = StaticAnalyze_load(data, ',', array, ARRAY_LEN);
return 0;
}
data in main is a pointer to a literal string that strtok cannot modify.
strchr could be used to identify the tokens.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define ARRAY_LEN (0x100)
#define OUTPUT_LEN (0x400)
unsigned int StaticAnalyze_load( char* data, char delimiter, int* array, unsigned int length ){
char *token = data;
int i=0;
while( i < ARRAY_LEN && token != NULL ) {
array[i] = atoi(token);
token = strchr(token, delimiter);
if ( token) {
++token;
}
i++;
}
for(i=0;i<3;i++) {
printf("%d\n", array[i]);
}
return length;
}
int main(int argc, const char * argv[]) {
char *data = "13,654,24,48,1,79,14456,-13,654,13,46,465,0,65,16,54,1,67,4,6,74,165,"
"4,-654,616,51,654,1,654,654,-61,654647,67,13,45,1,54,2,15,15,47,1,54";
int array[ARRAY_LEN]; // array, I need to fill-in with integers from the string above
unsigned int loaded = StaticAnalyze_load(data, ',', array, ARRAY_LEN);
return 0;
}

conflicting types for function returning a char array

Here's my code:
#include <stdio.h>
#include <string.h>
char input_buffer[1000];
void get_substring(){
int i;
int length;
printf("Please enter a string:\n");
scanf("%[^\n]s", input_buffer);
printf("Index of first character of substring:\n");
scanf("%d", &i);
printf("Length of substring:\n");
scanf("%d", &length);
printf("Substring is %.*s ", length, input_buffer + i);
}
int main(void) {
// your code goes here
//get_substring(0,4);
get_substring();
return 0;
}
That's my current code, I want to return a pointer of the input, instead of just displaying the substring. Sorry for the confusion everyone.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* getSubstring(char* str,size_t start, size_t length)
{
// determine that we are not out of bounds
if(start + length > strlen(str))
return NULL;
// reserve enough space for the substring
char *subString = malloc(sizeof(char) * length);
// copy data from source string to the destination by incremting the
// position as much as start is giving us
strncpy(subString, str + start, length);
// return the string
return subString;
}
int main(int argc, char* argv[])
{
char *str = "Hallo Welt!";
char *subStr = getSubstring(str,0,20);
if(subStr != NULL)
{
printf("%s\n",subStr);
free(subStr);
}
}
This solution should give you a hint how you would start with such a problem.

Finding last character

I'm new to C and trying to create a function that check a string and returns the last character.
I get the function to print the correct letter, but I cant figure out how to return it :/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char last_chr(char *c);
int main (int argc, const char * argv[]) {
char *text[15];
strcpy(text, "*find:last;char#");
last_chr(text); //debugging
//printf("last char: %c", last_chr(text)); //not working
return 0;
}
char last_chr(char *c) {
char *endchr;
char result;
int pos = strlen(c)-1;
endchr = c[pos];
//sprintf(result,"%s",endchr); //"EXEC_BAD_ACCESS"
putchar(endchr); //prints #
//putc(endchr, result); //"EXEC_BAD_ACCESS"
//printf(endchr); //"EXEC_BAD_ACCESS"
return result;
}
You don't assign result. You probably mean
result = c[pos];
instead of endchr = c[pos];
endchr is a character-pointer instead of a character.
#include <stdio.h>
#include <string.h>
char last_chr(char *c);
int main (int argc, const char * argv[]) {
char text[32];//char *text[15]
strcpy(text, "*find:last;char#");//length is 17
printf("last char: %c", last_chr(text));//#
return 0;
}
char last_chr(char *c) {
if(c == NULL || *c == '\0') return 0;
return c[strlen(c)-1];
}

Resources