How to divide a string to substring and assign another substring? - c

I want to divide *eString to substrings. Substrings should be like that:
y_{1} = y_{1}y_{m+1}y_{2m+1}...
y_{2} = y_{2}y_{m+2}y_{2m+2}...
y_{m} = y_{m}y_{2m}y_{3m}...
where y is the element of *eString, and y is the substring of these elements.
For instance, if an user expects the key length which is 5, there should be (string size / 5) substrings. y_{1} has to contain the fist element of each divided substring. So, how can I implement this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define ALPHA 26
char *ReadFile(char *);
int main(int argc, char *argv[])
{
double frequency[ALPHA] = {0};
int c = 0;
int keylen = 0;
int counter = 0;
double indexofCoincidence = 0,total = 0;
const char *eString = ReadFile("cipher.txt");
int len = 0;
if (eString) {
puts("The encrypted text is:");
puts(eString);
puts("");
len = strlen(eString);
printf("The length of text is %d\n",len);
}
puts("");
while(eString[c]!= '\0'){
if(eString[c]>= 'a' && eString[c]<='z')
frequency[eString[c]-'a']++;
c++;
}
puts("The letters frequencies are :\n");
for(c=0; c<ALPHA;c++){
if(frequency[c]!= 0)
printf("%c : %.3f\t",c+'a',(frequency[c]/len));
total += (frequency[c]*(frequency[c]-1));
}
indexofCoincidence = (total/((len)*(len-1)));
printf("\n\nIndex of Coincidence : %.3f\n",indexofCoincidence);
if(indexofCoincidence < 0.060){
printf("\nIt looks like randomly.\n");
}
printf("Enter the your expected key length : ");
scanf("%d",keylen);
printf("\n");
char *y;
while(counter != keylen)
{
for(int i = 0; i<(len/keylen);i++){
y[counter] = *eString();
}
counter++
}
return EXIT_SUCCESS;
}

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void){
char *eString = "The quick brown fox jumps over the lazy dog";
int keylen = 5;
int len = strlen(eString);
int y_len = (len + keylen) / keylen + 1;
int i,j;
char **y = malloc(keylen * sizeof(*y));
for(i=0; i < keylen; ++i){
y[i] = malloc(y_len * sizeof(**y));
}
char *p = eString;
i = j = 0;
while(*p){
y[i % keylen][j] = *p++;
y[i % keylen][j+1] = 0;
if(++i % keylen == 0)
++j;
}
//check print & deallocate
for(i = 0; i < keylen; ++i){
printf("y_{%d} : %s\n", i+1, y[i]);
free(y[i]);
}
free(y);
return 0;
}

Related

How to append parts of a string in a char array?

I need to split the string of n size and append in an array.
For example:
input:
abcdefghi
4
output:
[abcd,bcde,cdef,defg,efgh,fghi]
My code giving wrong answer:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "abcdefghi";
char result[100];
for(int i=0;i<strlen(str);i++){
strncat(result, str, str[i]+4);
}
printf("result: %s\n ", result);
}
My output:
abcdefgiabcdefgiabcdefgiabcdefgiabcdefgiabcdefgiabcdefgiabcdefgi
What mistake have I made??
Would you please try the following:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "abcdefghi";
char result[100];
int n = 4;
int i, j;
char *p = result; // pointer to the string to write the result
*p++ = '['; // left bracket
for (i = 0; i < strlen(str) - n + 1; i++) { // scan over "str"
for (j = i; j < i + n; j++) { // each substrings
*p++ = str[j]; // write the character
}
*p++ = i == strlen(str) - n ? ']' : ','; // write right bracket or a comma
}
*p++ = '\0'; // terminate the string with a null character
printf("result: %s\n", result); // show the result
return 0;
}
Output:
result: [abcd,bcde,cdef,defg,efgh,fghi]
Might this work for you?
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "abcdefghijklmno";
char result[100][100];
int nSplit = 4; //Split size
int nLength = strlen (str); //Lenth of the string
int nTotalString = nLength - nSplit; //total possibilities
int nStrCount = 0;
for (int i = 0; i <= nTotalString ; i ++)
{
for (int j = 0; j < nSplit; j++)
result[nStrCount][j] = str[i + j];
nStrCount++;
}
//print array
printf ("result:[");
for (int k = 0; k < nStrCount; k++)
printf ("\"%s\" ", result[k]);
printf ("]");
return 0;
}

Iterate Over Char Array Elements in C

This code is supposed to take a user's input and convert it to binary. The input is grouped into an integer array to store character codes and/or adjacent digits, then each item in the integer array is converted to binary. When the user types "c357", "c" should be converted to 99, then converted to binary. Then, "357" should be converted to binary as well. In the main() function, strlen(convert) does not accurately represent the number of items in array convert, thus only iterating over the first array item.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <unistd.h>
#include <string.h>
#define EIGHT_BITS 255
#define SIXTEEN_BITS 65535
#define THIRTY_TWO_BITS 4294967295UL
// DETERMINE NUMBER OF BITS TO OUTPUT
int getBitLength(unsigned long d) {
int l;
if (d <= EIGHT_BITS) {
l = 8;
}
else if (d > EIGHT_BITS && d <= SIXTEEN_BITS) {
l = 16;
}
else if (d > SIXTEEN_BITS && d <= THIRTY_TWO_BITS) {
l = 32;
}
return l;
}
// CONVERT INPUT TO BINARY VALUE
char* convertToBinary(unsigned long int decimal) {
int l = getBitLength(decimal);
static char b[33];
char bin[33];
int i, j, k = 0, r;
b[33] = '\0';
bin[33] = '\0';
printf("Bits................ %ld\n", l);
// creates array
for (i = 0; i < l; i++) {
r = decimal % 2;
decimal /= 2;
b[i] = r;
}
// reverses array for binary value
for (j = l - 1; j >= 0; j--) {
bin[k] = b[j];
strncpy(&bin[k], &b[j], l);
snprintf(&bin[k], l, "%d", b[j]);
k++;
}
printf("Binary Value: %s\n", bin);
return bin;
}
unsigned long int* numbersToConvert(char* input) {
const int MAX_INPUT = 20;
int i, k = 0, z = 0;
char numbers[MAX_INPUT];
unsigned long int *toConvert = malloc(MAX_INPUT * sizeof(int));
numbers[MAX_INPUT] = '\0';
for (i = 0; i < strlen(input); i++) {
if (isdigit(input[i])) {
numbers[z] = input[i];
if (!isdigit(input[i + 1])) {
toConvert[k] = strtol(numbers, NULL, 10);
printf("----- %ld -----\n", toConvert[k]);
z = 0;
}
else {
z++;
}
}
else {
printf("----- %c -----\n", input[i]);
printf("Character Code: %d\n", input[i]);
toConvert[k] = (unsigned long int) input[i];
}
k++;
}
return toConvert;
}
int main(void) {
const int MAX_INPUT = 20;
int i, p;
char input[MAX_INPUT];
unsigned long int* convert;
printf("------- Input --------\n");
scanf("%s", input);
input[MAX_INPUT] = '\0';
// PRINT INPUT AND SIZE
printf("\nInput: %s\n", input);
convert = numbersToConvert(input);
convert[MAX_INPUT] = '\0';
printf("strlen: %ld\n", strlen(convert));
for (i = 0; i < strlen(convert); i++) {
printf("num array: %ld\n", convert[i]);
convertToBinary(convert[i]);
}
return 0;
}
I have attempted to null terminate each string to prevent undefined behavior. I am unsure if certain variables, if any, are meant to be static.
It is hard to read your code.
Here you have something working (converting the number to binary):
static char *reverse(char *str)
{
char *end = str + strlen(str) - 1;
char *saved = str;
int ch;
while(end > str)
{
ch = *end;
*end-- = *str;
*str++ = ch;
}
return saved;
}
char *tostr(char *buff, unsigned long long val)
{
if(buff)
{
char *cpos = buff;
while(val)
{
*cpos++ = (val & 1) + '0';
val >>= 1;
}
*cpos = 0;
reverse(buff);
}
return buff;
}
int main()
{
char buff[128];
printf("%s\n", tostr(buff, 128));
}
https://godbolt.org/z/6sRC4C

Caesar Cipher not returning correct key

So my decrypter program seems to not be able to find the key and implement it by itself. I noticed that if I changed the key to equal -5 which is the correct key it would print out the decrypted text correctly. However I am unable to figure out how to make the program figure it out by itself without having me to put it in manually. Any help would be greatly appreciated! Thank you!
rotUtils.h
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "rotUtils.h"
int rotate(int c, int n){
if (n == 0) return c;
int nRot = abs(n) % (RANGECHAR + 1);
if(n > 0)
return rotatePlus(c + nRot);
else
return rotateMinus(c - nRot);
}
int rotatePlus(int sum){
int diff = sum - MAXCHAR;
if (sum > MAXCHAR) sum = MINCHAR + diff - 1;
return sum;
}
int rotateMinus(int sum){
int diff = MINCHAR - sum;
if (sum < MINCHAR) sum = MAXCHAR - diff + 1;
return sum;
}
decrypt.cpp
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include "rotUtils.h"
bool solved( char decodearr[], char dictarr[][30], int size1, int size2){
char* compared;
bool result = false;
for(int j = 0; j < size2; j++){
compared = strstr( decodearr, dictarr[j]);
}
if( compared != '\0'){
result = true;
}
return result;
}
int decode( char codearr[], char dictarr[][30], int size1, int size2)
{
bool solution = false;
int key = -50; This is where I had to change it to -5 to solve
char decodearr[10000];
while(solution == false && key < 51)
{
for( int i = 0; i < size1; i++)
{
if(!isspace(codearr[i]))
{
decodearr[i] = rotate(codearr[i], key);
}
else
decodearr[i] = codearr[i];
}
solution = solved( decodearr, dictarr, size1, size2);
if( solution == false)
{
key++;
}
}
for( int j = 0; j < size1; j++)
{
codearr[j] = decodearr[j];
}
return key;
}
int main( int argc, char* argv[])
{
char* file = argv[1];
char* dictionary = argv[2];
char code[10000];
char dict[30000][30];
FILE* codeFile;
codeFile = fopen(file, "r");
int i = 0;
int j = 0;
int key;
FILE* dictFile;
dictFile = fopen(dictionary, "r");
while(!feof(codeFile))
{
code[i] = fgetc(codeFile);
i++;
}
code[ i ]= '\0';
fclose(codeFile);
while(!feof(dictFile))
{
fscanf(dictFile, "%s", dict[j]);
j++;
}
key = decode(code, dict, i, j);
fclose(dictFile);
for(int k = 0; k < i; k++)
{
printf("%c", code[k]);
}
printf( "\nThe key is: %d\n", key);
return 0;
}
Solved() will only return true if there is a match on the last dictionary word currently, you have to move that check inside. You could print to screen whenever you find a key that has a match on your dictionary and/or keep a list of possible keys then print after you are done with them all, right now you would exit as soon as you find any match even if it was just luck.

Counting characters in a string or file

I have the following code:
#include "stdafx.h"
#include "string.h"
#include "ctype.h"
/*selection sort*/
void swap(int A[], int j, int k)
{
int p = A[k];
int i;
for (i = 0; i < (k - j); i++)
{
A[k - i] = A[k - i - 1];
}
A[j] = p;
}
/*greatest number in an array*/
int max(int A[], int N, int k)
{
int max = k, i;
for (i = k; i < N; i++)
{
if (A[max] < A[i])
max = i;
}
return max;
}
int count_nonspace(const char* str)
{
int count = 0;
while(*str)
{
if(!isspace(*str++))
count++;
}
return count;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[256];
int i = 0, j = 0, count[256] = { 0 };
char string[100] = "Hello world";
for (i = 0; i < 100; i++)
{
for (j = 0; j<256; j++)
{
if (tolower(string[i]) == (j))
{
count[j]++;
}
}
}
for (j = 0; j<256; j++)
{
printf("\n%c -> %d \n", j, count[j]);
}
}
Program is calculating the number of apperances of each character in a string. Now it prints the number of apperances of all 256 characters, whereas i want it to prinf only the character with greatest number of apperances in a string. My idea was to use the selection sort method to the array with the nubmer of apperances, but this is not working, thus my question is how to printf only the character with the greatest number of apperances in the string?
If anybody would have doubts, this is NOT my homework question.
EDIT: I've just noticed that this code printf apperances of characters begining with "j" why is that?
I started typing this before the others showed up, so I'll post it anyway. This is probably nearly the most efficient (increasing efficiency would add some clutter) way of getting an answer, but it doesn't include code to ignore spaces, count characters without regard to case, etc (easy modifications).
most_frequent(const char * str)
{
unsigned counts[256];
unsigned char * cur;
unsigned pos, max;
/* set all counts to zero */
memset(counts, 0, sizeof(counts));
/* count occurences of each character */
for (cur = (unsigned char *)str; *cur; ++cur)
++counts[*cur];
/* find most frequent character */
for (max = 0, pos = 1; pos < 256; ++pos)
if ( counts[pos] > counts[max] )
max = pos;
printf("Character %c occurs %u times.\n", max, counts[max]);
}
Create an array with your char as index.
Keep incrementing the value in the array based on the characters read.
Now get the max out of the array which gives you the most occurring char in your input.
Code will look like:
#include <stdio.h>
#include<string.h>
#include<stdlib.h>
int main(void) {
char buf[100];
int i=0,max =0,t=0;
int a[256];
memset(a,0,sizeof(a));
fgets(buf,100,stdin);
buf[strlen(buf)-1] = '\0';
while(buf[i] != '\0')
{
a[(int)buf[i]]++;
i++;
}
i=0;
for(i=0;i<256;i++)
{
if(a[i] > max)
{
max = a[i];
t = i;
}
}
printf("The most occurring character is %c: Times: %d",t,max);
return 0;
}
Here is a solution for that, based on your own solution, and using qsort().
#include <string.h>
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
struct Frequency
{
int character;
int count;
};
int compare(const void *const lhs, const void *const rhs)
{
return ((struct Frequency *)rhs)->count - ((struct Frequency *)lhs)->count;
}
int main(int argc, char* argv[])
{
int i = 0, j = 0;
struct Frequency count[256];
memset(&count, 0, sizeof(count));
char string[100] = "Hello world";
for (i = 0 ; i < 100 ; i++)
{
for (j = 0 ; j < 256 ; j++)
{
count[j].character = j;
if (tolower(string[i]) == j)
{
count[j].count += 1;
}
}
}
qsort(count, sizeof(count) / sizeof(*count), sizeof(*count), compare);
/* skip the '\0' which was counted many times */
if (isprint(count[1].character))
printf("\nThe most popular character is: %c\n", count[1].character);
else
printf("\nThe most popular character is: \\%03x\n", count[1].character);
for (j = 0 ; j < 256 ; j++)
{
if (isprint(count[j].character))
printf("\n%c -> %d \n", count[j].character, count[j].count);
else
printf("\n\\%03x -> %d \n", count[j].character, count[j].count);
}
}
notice that the '\0' is set for all the remainig bytes in
char string[100] = "Hello world";
so the count of '\0' will be the highest.
You could use strlen() to skip '\0', in the counting loop, but don't
for (i = 0 ; i < strlen(string) ; ++i) ...
do it this way
size_t length = strlen(string);
for (i = 0 ; i < length ; ++i) ...

How to write a getline function in C?

I know that getline is C++ standard but I need to read a line of digits:
123856
and save it to an array. But how to do this without spaces between given (as input) digits? I want a user input to be:
123856 (with no spaces) and then save it to an array (n element array) and after that, I want my array to look like this:
array[0] = 1;
array[1] = 2;
array[2] = 3;
array[3] = 8;
array[4] = 5;
array[5] = 6;
But how to make it in C, without a getline?
This is NOT what I want:
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdbool.h>
int main(int argc, char **argv)
{
int t[4];
int i;
for(i=0; i<4; i++)
scanf("%d", &t[i]);
for(i=0; i<4; i++)
printf("%d\n", t[i]);
return 0;
}
If I understood you correct, the following should do it:
read the whole line
loop through the string as long as you get digits or the string ends
for every digit, place it's value in your array and increase the index by 1
while( ( c = getchar()) != EOF && c != '\n' && i < max ) {
/* If desired, add check for value outside of 0-9 */
array[ i++ ] = c - '0';
...
}
char arr[] = "1234567";
int intarr[10];
int count = 0;
for (char* ptr = arr; *ptr; ptr++) {
intarr[count] = *ptr - '0';
count++;
}
try this
#include <stdio.h>
#include <string.h>
main (int argc, char *argv[])
{
FILE *f;
int i=0;
int j=0;
char output[100];
char* output1[100];
char string[100];
char delims1[] = " ";
char delims2[] = "*";
char* result = NULL;
char* result3 = NULL;
int num;
//for (j=0; j<2; j++)
//{
//printf("%s",delims9[6]);
//}
f = fopen("text.txt","r");
//
while( fgets(string,sizeof(string),f) )
{
result = strtok( string, delims1 );
while( result != NULL )
{
output1[i]=result;
printf("%s\n",output1[i]);
result = strtok( NULL, delims1 );
i++;
}
for (num = 0; num < 100; i++ ) //
{ // Error On this array
printf("%s\n", output1[i]); //
} //
}
printf("\n%d",i/3+1);
return 0 ;
}
Ok, without using any string.
int digits = 123856;
int numofdigits = 1 + floor(log10(digits));
int digits_arr[numofdigits];
int i;
for(i = numofdigits-1; i >= 0; i--) {
digits_arr[i] = (int)floor(digits / pow(10, i)) % 10;
}
Try the below link... Same question asked here and get solution....
convert an integer number into an array
char * convertNumberIntoArray(unsigned int number) {
unsigned int length = (int)(log10((float)number)) + 1;
char * arr = (char *) malloc(length * sizeof(char)), * curr = arr;
do {
*curr++ = number % 10;
number /= 10;
} while (number != 0);
return arr;
}

Resources