Split String into Tokens - c

*Can someone please help me with this function. I'm trying to separate the string input into tokens and also shift each token some by some specified amount. *
char *tokenize(char *f, int shift){
const char delim[] = " .;\n\t";
char *pa = f; //points to the beginning of *f
//size of *f
int i;
int stringSize = 0;
for(i = 0; f[i] != '\0'; i++)
{
stringSize++;
}
//put string in array to pass to strtok function
char newString[stringSize];
int j;
for(j = 0; j < stringSize; j++)
{
newString[j] = *f;
f++;
}
//break the words up into sub-strings without the delimiters
char *word = strtok(newString, delim);
while(word != NULL)
{
word = strtok(NULL, delim);
word = stringShift(word, shift);
//printf("After being shifted %d = %s\n", shift, word);
}
return pa;
}
/*Shift Function*/
char *stringShift(char *s, int k){
int i;
for(i = 0; s[i] != '\0'; i++)
{
s[i] += k;
}
return s;
}

I think this should serve the purpose ok, as far as I understand it
char* addWordToArr(char *arr,char *word)
{
int i;
for(i =0;i<strlen(word);i++)
{
*arr++ = word[i];
}
*arr++ = ' ';
return arr;
}
char *tokenize(char *f, int shift){
const char delim[] = " .;\n\t";
int stringSize = strlen(f);
//put string in array to pass to strtok function
char newString[stringSize+1];
int j;
for(j = 0; j < stringSize; j++)
{
newString[j] = *f;
f++;
}
newString[stringSize] = '\0'; //null terminate
char *rVal = malloc(sizeof(char) * (stringSize +1)); //The total length of the tokenized string must be <= the original string
char *writePtr = rVal;
//break the words up into sub-strings without the delimiters
char *word = strtok(newString, delim);
word = stringShift(word, shift);
writePtr = addWordToArr(writePtr,word);
while(word != NULL)
{
word = strtok(NULL, delim);
if(word)
{
word = stringShift(word, shift);
writePtr = addWordToArr(writePtr,word);
}
}
writePtr = '\0';
return rVal;
}
which produces:
string before shift bish;bash;bosh hyena trout llama exquisite underwater dinosaur
string after shift dkuj dcuj dquj j{gpc vtqwv nncoc gzswkukvg wpfgtycvgt fkpqucwt
The stringShift function is unchanged

Related

Removing char from string C

I'm learning C now
I need to make a program that remove char that I'll input from string. I've seen an algorithm and I write this code
#define MAX_LEN 200
int main()
{
char str[MAX_LEN];
char rem;
int i = 0;
printf("Enter the setence:");
gets(str);
printf("\nEnter the char to remove");
rem = getchar();
char* pDest = str;
char* pS= str;
printf("sent:\n%s", str);
while (str[i]!='\0'){
if (*pDest != rem) {
*pDest = *pS;
pDest++;
pS++;
}
else if (*pDest == rem) {
pS++;
}
i++;
}
*pDest = '\0';
while (str[i] != '\0') {
printf("number%d", i);
putchar(str[i]);
printf("\n");
i++;
}
}
But it returns nothing, like the value str gets, i think \0 and retuns nothing.
May you help me to find the problem?
Use functions!!
If dest is NULL then this function will modify the string str otherwise, it will place the string with removed ch in dest.
It returns reference to the string with removed character.
char *removeChar(char *dest, char *str, const char ch)
{
char *head = dest ? dest : str, *tail = str;
if(str)
{
while(*tail)
{
if(*tail == ch) tail++;
else *head++ = *tail++;
}
*head = 0;
}
return dest ? dest : str;
}
int main(void)
{
char str[] = "ssHeslsslsos sWossrlssd!ss";
printf("Removal of 's' : `%s`\n", removeChar(NULL, str, 's'));
}
It would be easier to use array style indexing to go through the string. For example use str[i] = str[i + 1] instead of *pstr = *other_pstr. I leave this incomplete method, since this looks like homework.
int main()
{
char str[] = "0123456789";
char ch = '3';
for (int i = 0, len = strlen(str); i < len; i++)
if (str[i] == ch)
{
for (int k = i; k < len; k++)
{
//Todo: shift the characters to left
//Hint, it's one line
}
len--;
}
printf("%s\n", str);
return 0;
}
I just added new char array char dest[MAX_LEN] that store string with deleted symbols:
#define MAX_LEN 200
int main()
{
char str[MAX_LEN];
char rem;
int i = 0;
printf("Enter the setence:");
gets(str);
printf("\nEnter the char to remove");
rem = getchar();
char dest[MAX_LEN] = "\0";
char* pDest = dest;
char* pS = str;
printf("sent:\n%s", str);
while (str[i]!='\0')
{
if (*pS != rem)
{
*pDest = *pS;
pDest++;
pS++;
}
else if (*pS == rem)
{
pS++;
}
i++;
}
i = 0;
printf("\nres:\n %s \n", dest);
while (dest[i] != '\0') {
printf("number%d", i);
putchar(dest[i]);
printf("\n");
i++;
}
}

How to split a text into two dimensional array in c

I'm trying to split this string:
this is a text file
looking for the word cat
the program should print also cats
and crat and lcat but it shouldn’t
print the word caats
into a two dimensional arrays such that every line in the text is a line in the array.
For example:
lines[0][0] = 't'
lines[0][1] = 'h'
and so on. For now, this is my code:
void print_lines(char txt[]){
char lines[SIZE][SIZE];
int num_of_lines = fill_lines(txt, lines);
printf("lines: %d\n",num_of_lines );
int i;
for (i = 0; i < num_of_lines; i++)
{
printf("%s\n", lines[i]);
}
}
int fill_lines(char txt[], char lines[][]){
char copy[strlen(txt)];
memcpy(copy, txt, strlen(txt));
char *line = strtok(copy, "\n");
int i = 0;
while(line != NULL){
strcpy(lines[i][0], line);
line = strtok(NULL, "\n");
i++
}
return i + 1;
}
The problem I'm currently dealing with is an error in strcpy(lines[i], line) that reads:
expression must be a pointer to a complete object type
I have also tried memcpy(lines[i], line, strlen(line)).
Any help would be much appreciated.
I think this should work for you
Here I used '\n' as a delimiter
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
char **str_split(char *a_str, const char a_delim)
{
char **result = 0;
size_t count = 0;
char *tmp = a_str;
char *last_comma = 0;
char delim[2];
delim[0] = a_delim;
delim[1] = 0;
/* Count how many elements will be extracted. */
while (*tmp)
{
if (a_delim == *tmp)
{
count++;
last_comma = tmp;
}
tmp++;
}
/* Add space for trailing token. */
count += last_comma < (a_str + strlen(a_str) - 1);
/* Add space for terminating null string so caller
knows where the list of returned strings ends. */
count++;
result = malloc(sizeof(char *) * count);
if (result)
{
size_t idx = 0;
char *token = strtok(a_str, delim);
while (token)
{
assert(idx < count);
*(result + idx++) = strdup(token);
token = strtok(0, delim);
}
assert(idx == count - 1);
*(result + idx) = 0;
}
return result;
}
int main()
{
char text[] = "this is a text file\nlooking for the word cat\nthe program should print also cats\nand crat and lcat but it shouldn’t\nprint the word caats";
char **tokens;
printf("ORIGINAL TEXT:\n%s\n\n", text);
tokens = str_split(text, ',');
if (tokens)
{
int i;
for (i = 0; *(tokens + i); i++)
{
printf("%s\n", *(tokens + i));
free(*(tokens + i));
}
printf("\n");
free(tokens);
}
return 0;
}

C - Copy a char into a char*

I got some troubles while I'm trying to set a char into a char* ("string")
I got lines, which is all the txt lines I fetched before, and now I'm trying to assign a char to my char*, to filter it.
Here is my actual code :
void TreatDatas(char** lignes, int sizeLignes){ // all the lines, and the size of it.
char** finalArray;
finalArray = malloc(2048 * sizeof(char*));
int sizeOfFinalArray = 0;
int i;
int j;
char* s;
char* savedCurrentString = "";
int sizeOfCurrentString = 0;
for (i = 0; i< sizeLignes; i++){
s = lignes[i];
for (j = 0; j < strlen(s); j++){ // I don't pass the first condition the first loop
if (s[j] == ',' || s[j] == '.' || s[j] == ' ' || s[j] == '\n' || s[j] == ';' || s[j] == ':'){ // Separators list
finalArray[sizeOfFinalArray] = malloc(strlen(savedCurrentString) + 1);
strcpy(finalArray[sizeOfFinalArray], savedCurrentString);
savedCurrentString = "";
sizeOfCurrentString = 0;
}else{
printf("%c , %s \n", s[j], savedCurrentString); // L - ""
printf("%d", sizeOfCurrentString); // 0
strncpy(savedCurrentString, s[j], 1); // error here
}
}
}
free(finalArray);
}
Ok I change a bit the code, now it's better, but seems to duplicate some elements. And I don't know why. Excuse me, I'm a C beginer, but I'm curious and trying to understand how that works.
void TreatDatas(char** lignes, int sizeLignes){
char** finalArray;
finalArray = malloc(2048 * sizeof(char*));
int sizeOfFinalArray = 0;
int i;
int j;
char* s;
char* savedCurrentString = "";
int sizeOfCurrentString = 0;
for (i = 0; i< sizeLignes; i++){
s = lignes[i];
printf("line : %d \n %s \n", i, s);
StringSpliter(s);
// for (j = 0; j < strlen(s); j++){
// finalArray[sizeOfFinalArray] = malloc(strlen(savedCurrentString) + 1);
// }
}
free(finalArray);
}
char * StringSpliter(char* input){
char separators[5][2] = {" ", ",", ";", ":", "."};
char ** buffer;
int bufferSize = 0;
int i;
for (i = 0; i < 5; i++){
char* token = strtok(input, separators[i]);
printf("%s", token);
while( token != NULL )
{
printf( " %s\n", token );
token = strtok(NULL, separators[i]);
}
}
printf("\n");
return "OSEF";
}
My output

reversing word. (null terminated c string char array). why isn't it working

am trying to reverse a char array and print it using %s. but its not working. am not getting anything printed. why is that? my code is pretty simple/
char* reverse(char* word){
int i = 0;
int length=0;
while (word[i] != '\0'){
i++;
}
length = i;
char* temp_word = malloc(length* sizeof(char));
for (i = 0; i < length; i++){
temp_word[i] = word[length - i];
word[i] = temp_word[i];
}
return word ;
}
temp_word[i] = word[length - i];
should probably be
temp_word[i] = word[length - i - 1];
If word[] is 3 characters long, word[3] is actually the null terminator.
This works ... you did not allocate space for Null terminator ... and you are overwriting by doing this 'word[i] = temp_word[i]' ...
#include <stdio.h>
#include <stdlib.h>
char *reverse(char *);
int main()
{
char sWord[10] = "PHONE";
char *temp = NULL;
printf("Before reverse() => %s\n", sWord);
temp = reverse(sWord);
printf("After reverse() => %s\n", temp);
return 0;
}
char *reverse(char *word)
{
int i = 0;
int length = 0;
while(word[i] != '\0')
{
i++;
}
length = i;
char *temp_word = malloc(length * (sizeof(char)+1)); // +1 here.
for (i = 0; i < length; i++)
{
temp_word[i] = word[length - (i+1)];
//word[i] = temp_word[i]; <== Do not need this.
}
temp_word[length] = '\0';
return temp_word ;
}

String manuplation in C

I hava a string, say ../bin/test.c, so how can i get its substring test?
I tried strtok api, but it seems not good.
char a[] = "../bin/a.cc";
char *temp;
if(strstr(a,"/") != NULL){
temp = strtok(a, "/");
while(temp !=NULL){
temp = strtok(NULL, "/");
}
}
Try this:
char a[] = "../bin/a.cc";
char *tmp = strrstr(a, "/");
if (tmp != NULL) {
tmp ++;
printf("%s", tmp); // you should get a.cc
}
#include <stdio.h>
#include <string.h>
int main(void){
char a[] = "../bin/a.cc";
char name[16];
char *ps, *pe;
ps = strrchr(a, '/');
pe = strrchr(a, '.');
if(!ps) ps = a;
else ps += 1;
if(pe && ps < pe) *pe = '\0';
strcpy(name, ps);
printf("%s\n", name);
return 0;
}
The ugly one solution:
char a[] = "../bin/a.cc";
int len = strlen(a);
char buffer[100];
int i = 0;
/* reading symbols from the end to the slash */
while (a[len - i - 1] != '/') {
buffer[i] = a[len - i - 1];
i++;
}
/* reversing string */
for(int j = 0; j < i/2; j++){
char tmp = buffer[i - j - 1];
buffer[i - j - 1] = buffer[j];
buffer[j] = tmp;
}

Resources