anagram in c with runtime error - c

Why do I get a runtime error?
Output Format
Print a single integer denoting the number of characters you must delete to make the two strings anagrams of each other.
We consider two strings to be anagrams of each other if the first string's letters can be rearranged to form the second string. In other words, both strings must contain the same exact letters in the same exact frequency
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
int cmpfunc (const void * a, const void * b){
return ( *(int*)a - *(int*)b );
}
char* concat(const char *s1, const char *s2){
char *result = malloc(strlen(s1)+strlen(s2)+1);//+1 for the zero-terminator
strcpy(result, s1);
strcat(result, s2);
return result;
}
int main(){
char* a = (char *)malloc(512000 * sizeof(char));
scanf("%s",a);
char* b = (char *)malloc(512000 * sizeof(char));
scanf("%s",b);
int l1 = strlen(a);
int l2 = strlen(b);
if(l1 != l2){
printf("String lengths do not match, exiting\n");
exit(1);
}
char * s;
for (int i = 0; i < l1; i++){
s = concat(a, b);
}
qsort(s, l1, sizeof(int), cmpfunc);
int range[26]={0};
for(int i=0;i<l1;i++){
int t = s[i] - 'a';
range[t]++;
}
int count = 0;
for(int i=0;i<=l1;i++){
count++;
}
printf("%d\n", count);
free(s);
free(a);
free(b);
return 0;
}

Related

separate numbers and string into text and numbers

I am trying to write code where I can separate string and numbers.
The string I have to separate it completely already the numbers I have to separate every 2 numbers.
My Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void getString(const char *str) {
char nums[50];
char alphas[50];
for (int i = 0; i < strlen(str); i++) {
if (isdigit(str[i]))
strcpy(nums, str);
if (isalpha(str[i]))
strcpy(alphas, str);
}
printf("str: %s\n", alphas);
printf("num: %d\n", atoi(nums));
}
int main() {
char *str = "one01two02three03";
getString(str);
return 0;
}
What I'm trying to do should return me as follows
str: onetwothree
num1: 01
num2: 02
num3: 03
The following parses the input and produces the correct output.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int *nums = NULL;
int num_count = 0;
char save_num(int n)
{
nums = realloc(nums, sizeof(int)*(num_count+1));
nums[num_count++] = n;
return '\0';
}
void getString(const char *str)
{
char* alpha = malloc(strlen(str)+1);
char* num = malloc(strlen(str)+1);
size_t i;
alpha[0] = '\0';
num[0] = '\0';
for (i = 0; i < strlen(str); i++)
{
if (isdigit(str[i]))
strncat(num, str+i, 1);
else if(isalpha(str[i]))
{
strncat(alpha, str+i, 1);
if(strlen(num) > 0)
num[0] = save_num(atoi(num));
}
}
if(strlen(num) > 0)
save_num(atoi(num));
printf("str: %s\n", alpha);
for(i = 0 ; i < num_count ; ++i)
printf("num%Zu: %02d\n", i+1, nums[i]);
free(alpha);
free(num);
}
int main()
{
char *str = "one01two02three03";
getString(str);
return 0;
}
This provides what you have asked for:
void getString(const char *str)
{
char one[10],two[10],three[10];
int x,y,z;
char a[10],b[10],c[10];
sscanf(str,"%[^0-9]""%[0-9]""%[^0-9]""%[0-9]""%[^0-9]""%[0-9]",a,one,b,two,c,three);
x = atoi(one);
y = atoi(two);
z = atoi(three);
printf("str: %s%s%s\n",a,b,c);
printf("num: %d\n",x);
printf("num: %d\n",y);
printf("num: %d\n",z);
}
Don´t forget to provide the declaration of getString before main():
void getString(const char *str);
So all together:
#include <stdio.h>
void getString(const char *str);
int main()
{
char *str = "one01two02three03";
getString(str);
return 0;
}
void getString(const char *str)
{
char one[10],two[10],three[10];
int x,y,z;
char a[10],b[10],c[10];
sscanf(str,"%[^0-9]""%[0-9]""%[^0-9]""%[0-9]""%[^0-9]""%[0-9]",a,one,b,two,c,three);
x = atoi(one);
y = atoi(two);
z = atoi(three);
printf("str: %s%s%s\n",a,b,c);
printf("num: %d\n",x);
printf("num: %d\n",y);
printf("num: %d\n",z);
}
Output:
str: onetwothree
num: 01
num: 02
num: 03
Since you have already set your strings 'nums' and 'alphas' there is no need to handle them dynamically.You should just copy the elements of the array str,one by one, to either the array num or the array alphas.
To distinguish different numbers just put a special character between numbers in the num array.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void getString(const char *str)
{
char nums[50];
char alphas[50];
int digits = 0;
int alpha = 0;
for (int i = 0; i < strlen(str); i++) {
if (isdigit(str[i])){
while(isdigit(str[i])){
nums[digits] = str[i];
i++;
digits++;
}
nums[digits]='\n';
digits++;
}
if(isalpha(str[i])){
alphas[alpha] = str[i];
alpha++;
}
}
printf("str: %s\n", alphas);
int n,p=0;
char subbuf[5];
for(n=0;n<digits;n++){
p=n;
while(nums[n]!='\n'){
n++;
}
memcpy(subbuf,&nums[p],n-p);
printf("num: %d\n", atoi(subbuf));
}
}
int main()
{
char *str = "01two02three03";
getString(str);
return 0;
}
Be aware that strcpy sets the pointer of the first argument to point to the second argument,this means that when you write strcpy(nums,str) in your code above, you copy the entire str string to the num several times.
Using an array for this question is not necessary, unless the array is to be used later. So my answer to this question is short and simple:
#include <stdio.h>
#include <stdbool.h>
void getString(const char *str)
{
bool in_number = false;
while (*str) {
if (*str >= '0' && *str <= '9') {
if (!in_number) { // Transition from a non-digit to digit
printf(": ");
in_number = true;
}
} else if (in_number) { // Transition from a digit to non-digit
putchar('\n');
in_number = false;
}
putchar(*str++);
}
putchar('\n');
}
int main(void)
{
char *str = "one01two02three03";
getString(str);
return 0;
}
The boolean variable in_number is used to catch the transitions from a digit character to a non-digit character and from a non-digit character to a digit character.

Create function which sorts 2 given sorted strings

Given two sorted strings, I need to merge these strings to one string, and make it sorted.
sort by the ASCII value. for example:
acdty, berz => abcdertyz
My code:
#include <stdio.h>
#include <stdlib.h>
char* PairSortedArrays(char a[], char b[]) {
char* c = (char*)malloc((sizeof(a) + sizeof(b)) * sizeof(char));
int i, aPos = 0, bPos = 0;
for (i = 0; i < sizeof(*c); i++) {
if ((int)(a[aPos]) <= (int)(b[bPos])) {
c[i] = a[aPos];
aPos++;
}
else {
c[i] = b[bPos];
bPos++;
}
}
return c;
}
int main()
{
printf("%s", PairSortedArrays("acdty", "berz"));
return 0;
}
The first problem is with sizeof(a). if I code: printf("%d", sizeof(a)); it prints 8, while I expect it to print 5.
The expression i < sizeof(*c) controling the for loop is the main culprit. The corrected version of your program could be: (I edited the code a bit)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* PairSortedArrays(const char a[], const char b[])
{
size_t i;
const size_t total_len = strlen(a)+strlen(b);
char *c = malloc(total_len + 1);
size_t aPos = 0, bPos = 0;
for (i = 0; i < total_len; i++) {
if (a[aPos] == '\0') {
strcpy(c + i, b + bPos);
break;
}
if (b[bPos] == '\0') {
strcpy(c + i, a + aPos);
break;
}
c[i] = a[aPos] < b[bPos] ? a[aPos++] : b[bPos++];
}
return c;
}
int main()
{
printf("%s\n", PairSortedArrays("acdty", "berz"));
printf("%s\n", PairSortedArrays("az", "ks"));
return 0;
}
The return value of malloc must be checked against NULL in a real program. Also there is a memory leak (easy to fix).
When working with strings in C, you will want to be using strlen() to see how long they are, not sizeof (which merely tells you what the size of a pointer is).
Also note that sizeof(char) is 1 by definition, so there's no need to say "* sizeof(char)" in your malloc
sizeof(a) will return the size of a pointer in this case which will be 8 bytes if you compile for 64 architecture.
you have to either pass the size of each string or loop the string characters until you reach the '\0' if the string is null-terminated.
You should consider using qsort:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int compare_chars(const void *p1, const void *p2)
{
return *(const char *)p1 - *(const char *)p2;
}
char *PairSortedArrays(char *a, char *b)
{
char *c = malloc(strlen(a)+strlen(b)+1);
strcpy(c, a);
strcat(c, b);
qsort(c, strlen(c), sizeof(char), compare_chars);
return c;
}
int main()
{
printf("%s", PairSortedArrays("acdty", "berz"));
return 0;
}

c string isn't added to string correctly and outputs □ when using printf

I've been programming a script where a string should be added to a string.
But the printf function in my code prints the first time □ the second time □□ and the third time □□□. It should print A,Ap, App.
Here's a quick overview of my code:
#include<stdio.h>
#include<stdlib.h>
int i = 0;
char * name[];
char * tok[];
int hello = 0;
void append(char* s, char c) {
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
int input(char data[]){
for(i=0; i<strlen(data); ++i){
append(tok, data[i]);
if(hello == 0){
append(name, tok);
strcpy(tok, "");
printf(name);
printf("\n");
}
}
return 0;
}
int main(){
input("App");
return 0;
}
The program has undefined behavior.
These tentative definitions
char * name[];
char * tok[];
in fact are equivalent to
char * name[1] = { NULL };
char * tok[1] = { NULL };
So for example this statement
int len = strlen(s);
invokes undefined behavior.
Or the function first parameter
void append(char* s, char c) {
and the supplied argument
append(tok, data[i]);
have different types. The type of the argument is char ** while the type of the parameter is char *.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int i = 0;
char name[99];
char tok[99];
int hello = 0;
void append(char *s, char c) {
int len = strlen(s);
s[len] = c;
s[len+1] = '\0';
}
int input(char *data){
for(i=0; i<strlen(data); ++i)
{
append(tok, data[i]);
printf(tok);
printf("\n");
}
return 0;
}
int main(){
input("App");
return 0;
}

Extract all numbers of N digits from a string in C

I want to get all numbers from a specific string but, these numbers could be more than one digit long as (15, 587, ... exc). Here is what I did "my own code":
int firstIndxOfNumb(char* str, int startIndx, int len) {
int i, val;
i = startIndx;
while (str[i] && i < len) {
val = str[i];
if (isdigit(val))
return i;
i++;
}
return -1;
}
int lastIndxOfNumb(char* exp, int len, int indx1){
int i, curr;
for(i = indx1; i < len; i++){
curr = exp[i];
if(!isdigit(curr)){
return --i;
}
}
return 0;
}
int getNumb(char* exp, int len, int* indx1){
int indx2 = lastIndxOfNumb(exp, len, *indx1);
printf("indx1:%d\tindx2:%d\n", *indx1, indx2);
char temp[indx2-*indx1];
strncpy(temp, exp+*indx1, (size_t) (indx2-*indx1+1));
*indx1 = firstIndxOfNumb(exp, indx2+1, len);
return atoi(temp);
}
void main() {
char *s = "())(15*59";
int len = strlen(s);
int indx1;
indx1 = firstIndxOfNumb(s, 0, len);
printf("%d\n", getNumb(s, len, &indx1));
printf("\n%d", getNumb(s, len, &indx1));
}
And the goal is getting the two numbers (15, 59). The first call was okay but, the second is not "infinite-loop" with values index1:7 okay index2:0 isn't okay! Can you help me to make it working .....
The values are printed by printf(..); in getNum(); function ....
getNumb can be simplified as follows.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int getNumb(char **sp){
char *p = *sp;
while(*p && !isdigit((unsigned char)*p))//skip not digit
++p;
if(!*p)
return -1;//not find numbers (Don't include negative numbers as extract numbers)
int ret = strtol(p, &p, 10);
*sp = p;
return ret;
}
int main(void) {
char *s = "())(15*59";
char *sp = s;
printf("%d\n", getNumb(&sp));
printf("%d\n", getNumb(&sp));
}
When it contains a negative number.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <stdbool.h>
bool getNum(char **sp, int *v /* out */){
char *p = *sp;
while(*p && !isdigit((unsigned char)*p) && (*p!='-' || !isdigit((unsigned char)p[1])) )//skip not number
++p;
if(!*p)
return false;//not find numbers
*v = strtol(p, &p, 10);
*sp = p;
return true;
}
int main(void) {
char *s = "())(15*59+++-123,-2)";
char *sp = s;
int v;
while(getNum(&sp, &v))
printf("%d\n", v);
}

Function that return characters from string which occurrences is user definied

I really hitted the wall with this type of function. I need to make a function that returns characters from string.
user can enter any number and I need to find char in string where total number of occurrences is number that user specified.
Does someone knows how can it be done in C language?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int cmp(const void *a, const void *b){
unsigned char ac = *(unsigned char *)a;
unsigned char bc = *(unsigned char *)b;
return ac < bc ? -1 : ac > bc;
}
char *func(const char *str, size_t n){
size_t len = strlen(str);
char *dup = malloc(len + 1);
char temp[len + 1];//[256]
strcpy(dup, str);
qsort(dup, len, sizeof(*dup), cmp);
char *p = dup;
size_t i = 0;
while(*p){
char aChar[] = {*p, 0};
len = strspn(p, aChar);
if(len == n){
temp[i++] = *p;
}
p += len;
}
temp[i] = 0;
strcpy(dup, temp);
return dup;
}
int main(void){
char *occurs = func("111abcddaaa", 1);
for(char *p = occurs; *p; ++p){
printf("%c\n", *p);
}
free(occurs);
return 0;
}

Resources