Cut long strings into something shorter - c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 24
void rez(char **c, char *s, int n, int ks);
void rez(char **c, char *s, int n, int ks)
{
int t = 0, j = 0;
char *p;
p = strtok(s," ");
t = t + strlen(p);
if (strlen(p)>N) *(c+j)=(char*)malloc((strlen(p)+1)*sizeof(char));
else *(c+j)=(char*)malloc((N+1)*sizeof(char));
while(p!=NULL)
{
if (t>N)
{
*(*(c+j)+t) = '\0';
t = strlen(p) + 1;
j++;
if (t>N) *(c+j)=(char*)malloc(strlen(p)+1);
else *(c+j)=(char*)malloc(N+1);
}
strcat(*(c+j), p);
c[j][t]=' ';
p = strtok(NULL, " ");
t=t+strlen(p)+1;
}
c[j][t]='\0';
for(j=0; j<ks; j++)
{
printf("\n %s", *(c+j));
}
}
int main(void)
{
FILE *fin;
int n, ks;
char s1[2048], filename[256];
char **c;
printf("Enter the file name->");
scanf("%s", filename);
fin=fopen(filename,"r");
if (!fin)
{
printf ("Error\n");
return -1;
}
while (fscanf(fin, "%[^\n]", s1)==1)
{
fscanf(fin, "%*[ \n]");
printf("\n String: %s \n", s1);
n=strlen(s1);
ks=n/(N-1)+1;
c=(char **)malloc(ks*sizeof(char*));
rez(c, s1, n, ks);
}
fclose(fin);
return 0;
}
This code should cut long strings into some shorter, but it gives "core dumped" in gcc. It doesn't exit from while in void rez().
In my mind, strtok() works incorrectly.

This is wrong:
char r[1]=" ";
because the string literal " " is TWO characters! It is both a space and a NULL-terminator (which is at the end of every string in C. But you explicitly said it should only be a 1 character array.

Related

How to search for names by letters in a string Array?

Do anybody knows how to search for a name in a string array? If i register the name 'jacob' and search for cob I need to get jacob shown instead of not showing up anything. I don't know if strcmp is the right way to do it. Any ideas?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
struct name{
char name[MAX];
};
void getRegister(struct name name[], int *nrNames);
void getSearch(struct name name[], int nrNames);
int readLine(char s[], int length);
int main(){
int run=1;
struct name name[MAX];
int nrNames=0;
while(run){
char choice;
printf("\n (1)Register\n(2)Search\n(3)Quit\n");
scanf(" %c%*c", &choice);
if(choice=='1') getRegister(name, &nrNames);
if(choice=='2') getSearch(name, nrNames);
if(choice=='3') run=0;
}
return 0;
}
void getRegister(struct name name[], int *nrNames){
char input[MAX];
printf("Enter name: ");
readLine(input, MAX);
(*nrNames)++;
}
void getSearch(struct name name[], int nrNames){
int i;
char input[MAX];
printf("Enter name: ");
readLine(input, MAX);
if(i>=0){
printf("Name/s:\n");
for(i=0; i<nrNames;i++){
if(strcmp(input, name[i].name)==0){
printf("\n%s\n",name[i].name);
}
}
}
}
int readLine(char s[], int length){
int ch, i=0;
while(isspace(ch=getchar()));
while(ch!='\n' && ch!=EOF) {
if(i<length) s[i++]=ch;
ch = getchar();
}
s[i]='\0';
return i;
}
Try to search for the match in the array. The code below displays a position for each occurrence of the second array in the first array. It uses naive approach. There are more efficient algorithms like Knuth-Morris-Pratt or Boyer-Moore algorithm.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define MAX 20
int main(){
char c;
char name[MAX], search_name[MAX];
int i = 0, j = 0, match = 0, count = 0;
printf("Register name: ");
while ((c = fgetc(stdin)) != '\n') {
if (i < MAX){
name[i++] = c;
}
}
name[i] = '\0';
printf("Search name: ");
i = 0;
while ((c = fgetc(stdin)) != '\n') {
if (i < MAX){
search_name[i++] = c;
}
}
search_name[i] = '\0';
i=-1;
match = 0;
do {
i++;
j = 0;
do {
if (name[i+j] == search_name[j])
match = 1;
else {
match = 0;
break;
}
j++;
} while (search_name[j] != '\0');
if (match)
printf("Match on position %d ", i);
} while (name[i+j] != '\0');
printf("\n");
return 0;
}
I found the soulution myself. Here is the code for those who get stuck as I did.
void searchName(const struct varor reg[], int nrOfGoods){
int i;
char name[20];
printf("Enter name: ");
readLine(name, WORDLENGTH);//gets input
if(i>=0){
printf("\nId.number \t Name \t\t\t Quantity\n");
for(i=0; i<nrOfGoods;i++){
if(strstr(reg[i].name, name)!=NULL){ //this should do the job
printf("%-17d%-24s%-5d\n",reg[i].idnumber,reg[i].name.reg[i].quantity);
}
}
}
}

C language: try to implement IndexOf function

I try to learn C Language and something is not clear to me.
I want to write IndexOf function that search for char inside string and return the Index number.
I am running this under ubuntu and compile using this:
test1: test.c
gcc -g -Wall -ansi -pedantic test.c -o myprog1
This is what i have try:
int c;
int result;
printf("Please enter string: ");
scanf("%s", str1);
printf("Please enter char: ");
scanf("%d", &c);
result = indexof(str1, c);
printf("Result value: %d\n", result);
And this is my function:
int indexof(char *str, int c)
{
int i;
for (i = 0; i < strlen(str); i++)
{
if (str[i] == c)
return i;
}
return -1;
}
So my problem is that my function return -1 all the time
scanf("%c",&c)..you are getting input a character.
Working copy would besomethign like:-
char c; // you want to find the character not some integer.
int result;
printf("Please enter string: ");
scanf("%s", str1);
printf("Please enter char: ");
scanf("%d", &c);
result = indexof(str1, c);
printf("Result value: %d\n", result);
Working example:-
#include <stdio.h>
#include <string.h>
int indexof(char *str, char c)
{
int i;
for (i = 0; i < strlen(str); i++)
{
if (str[i] == c)
return i;
}
return -1;
}
int main()
{
char c;
int result;
char str1[100];
printf("Please enter string: ");
scanf("%s", str1);
printf("Please enter char: ");
scanf(" %c", &c);
result = indexof(str1, c);
printf("Result value: %d\n", result);
}
Since c is int:
int indexof(char *str, int c)
{
int i;
for (i = 0; i < strlen(str); i++)
{
if ((str[i]-'0') == c) // convert char to int
return i;
}
return -1;
}
write IndexOf function that search for char inside string and return the Index number.
You might like to have a look at the strchr() function, which can be used as shown below:
/* Looks up c in s and return the 0 based index */
/* or (size_t) -1 on error of if c is not found. */
#include <string.h> /* for strchr() */
#include <errno.h> /* for errno */
size_t index_of(const char * s, char c)
{
size_t result = (size_t) -1; /* Be pessimistic. */
if (NULL == s)
{
errno = EINVAL;
}
else
{
char * pc = strchr(s, c);
if (NULL != pc)
{
result = pc - s;
}
else
{
errno = 0;
}
}
return result;
}
You could call it like this:
size_t index_of(const char *, char);
#include <stdlib.h> /* for EXIT_xxx macros */
#include <stdio.h> /* for fprintf(), perror() */
#include <errno.h> /* for errno */
int main(void)
{
result = EXIT_SUCCESS;
char s[] = "hello, world!";
char c = 'w';
size_t index = index_of(s, 'w');
if ((size_t) -1) == index)
{
result = EXIT_FAILURE;
if (0 == errno)
{
fprintf("Character '%c' not found in '%s'.\n", c, s);
}
else
{
perror("index_of() failed");
}
}
else
{
fprintf("Character '%c' is at index %zu in '%s'.\n", c, index, s);
}
return result;
}

palindrome program (not working) i dont know why

I tried making a small program that would detect if you typed in a palindrome but for some reason, it just loops
ps I'm a beginner
#include <stdio.h>
#include <string.h>
int main(void)
{
char arr[100], arr1[100];
int i;
printf("type in a string\n\n");
gets(arr);
strrev(arr) == arr1;
for (i=0; arr==arr1; i++)
{
printf("%c is a palindrome\n", arr);
}
for (i=0; arr!=arr1; i++)
{
printf("%c is not a palindrome\n", arr);
}
return 0;
}
arr and arr1 are base address of the two arrays respectively which would be different.One simple Code is here
#include <stdio.h>
#include <string.h>
int main(void)
{
char arr[100], arr1[100];
int i;
printf("type in a string\n\n");
gets(arr);
int len=strlen(arr);
strcpy(arr1,arr);
strrev(arr);
for(i=0;i<len;i++){
if(arr1[i]!=arr[i]){
printf("Not palindrome");
return 1;
}
}
printf("Palindrome");
return 0;
}
Use fgets instead of gets.
The first character could be compared to the last character. Then move the indexes toward the center for subsequent comparisons.
#include <stdio.h>
#include <string.h>
int main(void) {
char arr[100] = "";
int first = 0;
int last = 0;
printf ( "type in a string\n\n");
if ( !fgets ( arr, sizeof arr, stdin)) {
printf ( "fgets problem\n");
return 0;
}
arr[strcspn ( arr, "\n")] = '\0';//remove newline
for ( first = 0, last = strlen ( arr) - 1; first <= last; first++, last--) {
if ( arr[first] != arr[last]) {
printf("%s is not a palindrome\n", arr);
return 0;
}
}
printf ( "%s is a palindrome\n", arr);
return 0;
}

Cryptography error with C

I am trying to create a program that can modify a text according to the user key. It seems to work well, until I input something and it adds extra things.
For example, if I add the word hello and a key of 3, it says khoor plus some extra weird characters. Can you tell me please what is the problem? Thank you very much.
#include <stdio.h>
#include <ctype.h>
#define MAXSIZE 100
void encrypt(senTence[], int key);
int main(void)
{
int userKey;
char sentence[MAXSIZE];
printf("Input the text that you want to encrypt:\n> ");
fgets(sentence, 99, stdin);
// printf("\nThe string that you wrote is:\n%s\n\n", sentence);
printf("Input the key:\n");
scanf("%d", &userKey);
//printf("\nThe key that you selected is: %d\n\n", userKey);
encrypt(sentence, userKey);
return 0;
}
void encrypt(const char senTence[], int key)
{
int i = 0;
char q[MAXSIZE];
for(i = 0; senTence[i] != '\0'; ++i)
{
if( ( isupper(senTence[i]) ) || ( islower(senTence[i]) ) )
{
q[i] = senTence[i] + (char)key;
}
else
{
q[i] = (senTence[i]);
}
}
printf("%s", q);
}
You didn't terminate the result string q in encrypt().
Add the following line before printf().
q[i] = '\0';
Another way is initialize q to all-zero:
char q[MAXSIZE] = {0};
You forgot to null terminate your array q, so using as a string will not be possible.
After you have performed the required operation on all the elements of the senTence and stored it to q, you need to null terminate q.
Use
q[i] = '\0';
printf("%s\n", q);
I ran the code, was giving a few warnings and an error, related to the function prototype. I fixed that and it is working fine now!
#include <stdio.h>
#include <ctype.h>
#define MAXSIZE 100
void encrypt(const char senTence[], int key);
int main(void)
{
int userKey;
char sentence[MAXSIZE];
printf("Input the text that you want to encrypt:\n> ");
fgets(sentence, 99, stdin);
// printf("\nThe string that you wrote is:\n%s\n\n", sentence);
printf("Input the key:\n");
scanf("%d", &userKey);
//printf("\nThe key that you selected is: %d\n\n", userKey);
encrypt(sentence, userKey);
return 0;
}
void encrypt(const char senTence[], int key)
{
int i = 0;
char q[MAXSIZE];
for(i = 0; senTence[i] != '\0'; ++i)
{
if( ( isupper(senTence[i]) ) || ( islower(senTence[i]) ) )
{
q[i] = senTence[i] + (char)key;
}
else
{
q[i] = (senTence[i]);
}
}
printf("%s", q);
}

Error: too few arguments to function 'strcmp'

I am having a few issues with my code. First: when I try to compile, I get error: too few arguments to function 'strcmp'. I have looked all over and made multiple changes and am still unable to get it to work. Second: when my code does compile (if I remove the strcmp part), it will not complete the count functions correctly. Can anyone please assist? Thank you!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int count(char array[], int size);
int stringLen(char array[]);
int convert(char ch);
int value, n;
int main()
{
//char * str;
//char s;
char a[100];
char b[100];
char c[100];
int charCount = stringLen(a);
int lCount = count(a, charCount);
printf("Enter your string: \n");
scanf("%s \n", a);
printf("Enter your string: \n");
scanf("%s \n", b);
printf("Enter your string: \n");
scanf("%s \n", c);
printf("The count is %d, length is %d\n", lCount, charCount);
int i;
for(i = 0; i < charCount; i++)
{
char c = a[i];
printf("Char %s = %d \n", &c, value);
}
n = strcmp(char string1[], char string2[], char string3[]);
printf("The first string in the alphabet is: %d \n", n);
return 0;
}
int stringLen(char array[])
{
char count;
int index;
while(array[index] !=0)
{
count++;
index++;
}
return count;
}
int count(char array[], int size)
{
int count;
int i;
for(i = 0; i < size; i++)
{
if(array[i] == 'a')
{
count ++;
}
else if(array[i] == 'A')
{
count ++;
}
}
return count;
}
This is not right way to use strcmp.
n = strcmp(char string1[], char string2[], char string3[]);
strcmp is used for compararison of string. See doc
int result = strcmp (string1,string2)
If strings are same, function will return 0.

Resources