Counting characters in char array? - c

Currently i'm trying to sort a paragraph based on first char of each word. I'm initializing two alphabetic (Upper and Lower) char arrays to compare to the first char of the word to the array index.
My Plan for the problem;
Initialize two Arrays with the Alphabet to know which alphabet goes before which.
Have a function that actually compares first char to the two Arrays.
return the words sorted :)
My problem is i'm trying to see if the two arrays have 26 characters to make sure every alphabet is counted for but it prints 1 and i have no idea why.
Code:
#include <stdio.h>
int main(int argc, const char * argv[]) {
char _alphabetUpperCase[100] = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R,","S","T","U","V","W","X","Y","Z"};
char _alpabetLowerCase[100] = {"a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"};
int i = 0;
int n = 0;
while(_alpabetLowerCase[i] != NULL)
{
n = n+1;
i++;
}
printf("%d\n",n);
return 0;
}

This "A" is not same as 'A'. You should assign 'A' to a character instead.
Replace all "" strings with corresponding '' characters. e.g.
char _alpabetLowerCase[100] = {'a','b','c' ... };

You want characters or strings? "a" is a string while 'a' is a character. From your definition of array it seems you want characters. So change your code for that as
char _alpabetLowerCase[100] = {"a", ...
Instead use
char _alpabetLowerCase[100] = {'a', 'b', ....

Try this:
#include <stdio.h>
int main(int argc, const char * argv[]) {
char _alphabetUpperCase[27] = {'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R,','S','T','U','V','W','X','Y','Z', '\0'};
char _alphabetLowerCase[27] = {'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z', '\0'};
int i = 0;
int n = 0;
while(_alphabetLowerCase[i] != '\0')
{
n = n+1;
i++;
}
printf("%d\n",n);
return 0;
}
Explanation: 'a' is char, but "a" is string. Also I added 27-th character to become sure that this loop will stop after 'z' (so I changed the array size to 27 (100 was correct too, but it is wrong to write arbitrary numbers when you can put correct value)).

Related

Returns a new string with characters from two other strings

Write a function common_char that takes two strings as arguments and returns a new string that contains a single copy of all characters that appear in either of the two strings.
For example, string1: hello; string2: world; the new string is : hellowrd (o and l were already in array from hello).
May use string function here.In other words, all characters in string1 are copied into the new string, but characters in string 2 are copied only characters that are not in string1. That is past exam question and the university did not provide answer. Here is my code.
#include <stdio.h>
#include <string.h>
char *common_char(char *string1, char *string2) {
int str_length1 = strlen(string1);
int str_length2 = strlen(string2);
char *new_string = malloc(str_length1+str_length2+1);
for (int index_1 = 0; index_1 < str_length1; index_1++) {
for (int index_2 = 0; index_2 < str_length2; index_2++) {
if (string1[index_1] == string2[index_2]) {
}
}
}
}
int main(void) {
return 0;
}
My idea is to find duplicate characters in string 2 and string 1 according to the nested loop, but there is a problem with the conditional statement, there is red line, also how to copy the character of the non-duplicate string? I know strcopy(), but how to remove the repeated characters?
I've come up with a solution that uses dynamic memory and resizes the result char* each time a new char must be added. There are two loops, the first iterates the b string and the second loop checks that non of char of the b string is repeated in the a string, if it is not repeated, then adds it. Hope you understand the realloc to resize dynamically the char* each time it must be added an element.
Firstly I initialize the result string to the size of string a so it can be all copied inside. The ordering method I think it is called bubble method.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* common_char(char* a, char* b) {
char* result = (char*)malloc(sizeof(char)*strlen(a)+1);
int i = 0;
int j = 0;
int repeated = 0;
strcpy(result,a);
for(i=0; i<strlen(b); i++) {
for(j=0; j<strlen(result); j++) {
if(b[i] == a[j]) {
repeated = 1;
}
}
if(!repeated) {
result = (char*)realloc(result,strlen(result)+sizeof(char));
result[strlen(result)] = b[i];
result[strlen(result)+1] = '\0';
}
repeated = 0;
}
return result;
}
int main()
{
char a[] = "hello";
char b[] = "world";
char* result = common_char(a,b);
printf("%s", result);
return 0;
}
EDIT: I've modified the code to make it function. About the comment of memory allocation, I've modified the declaration of result to give it space for the '\0'. When doing the realloc, I've already considered that the realloc does not increment the strlen() because strlen() is a counter till the '\0' not of the size of the variable.

How do I calculate count times for every char array with struct?

struct Page{
char data[50];
int count = 0; // ?
};
Page page[50];
I don't know how to save count for every char array.
for exmaple:
input: a c b
page[i].data[0] = a; // a_count = 1
page[i].data[1] = c; // c_count = 1
page[i].data[2] = b; // b_count = 1
my ideas is
paga[i].data[0].count++;
but, I don't know how to implement with struct.
Instead of a single integer count, you need an array to solve this issue. So you can define Page in the following way:
typedef struct Page
{
char data[50];
int countChar[TOTAL_CHARS];
} Page;
Now, we can't simply initialize an array inside a struct like we can in a function. So we have to manually initialize countChar[] with 0. However, there is a trick that can save you from this tiresome process. And the trick is to use a macro like this:
#define NEW_PAGE { "", {0} }
and use it in the following way:
Page page[50] = NEW_PAGE;
Now, all you have to do is map the character to the index of countChar[] and increment its value by 1. This can be done in the following way:
page[0].countChar[ch - 'a']++;
Here, ch is the character from input. Considering all the input will be lowercase letters, subtracting ch with 'a' will produce the required index that represent frequency of character ch. If the possible value of ch were all ASCII characters, we would simply replace 'a' with '\0' and change size of countChar[] accordingly.
Here's a code that tests this idea:
#include<stdio.h>
#define NEW_PAGE { "", {0} }
#define TOTAL_CHARS 26
typedef struct Page
{
char data[50];
int countChar[TOTAL_CHARS];
} Page;
int main()
{
Page page[50] = NEW_PAGE;
char input[] = "hello world";
char ch;
int i = 0;
int frequency;
while(input[i] != '\0')
{
ch = input[i];
page[0].data[i] = ch;
page[0].countChar[ch - 'a']++;
i++;
}
for(i=0; i<TOTAL_CHARS; i++)
{
frequency = page[0].countChar[i];
if(frequency != 0)
printf("%c is present %d times\n", ('a'+i), frequency);
}
return 0;
}
Instead of having a single int, you could have an array of integers of length 26. This would hold the count of each lowercase letter in the array.
The integer values for lowercase letters range from 97 - 122. To correspond each letter to an index in a 26 length array, you need to subtract 97 from the integer value of each char so that each char can correspond to an index from 0 - 25.
So your struct should look something like this:
struct Page{
char data[50];
int count[26];
};
If you had a char called letter, the way you would find the correct index of the count array and increment it would be:
int index = (int)letter - 97;
count[index]++;

How to count non-zero occurrences of a char in C?

I am new in C programming. I would like to ask how I can store a char in a char array? The reason why I want to do it is because I get a char from a computation I make. This computation returns a char consisting of 4. I want to look through every character of the 4 and check if they are "0". If not, then I will increment by one. This is an example of a substitution: "0xf3"- I am trying to compute the Hamming Weight of a substitution. This is how I try to count how many non-zero the char consists of:
#include <stdio.h>
int main()
{
char x = "0xf3";
char s[10] = x;
int lingh = strlen(s);
for (int i = 0; i<lingh;i++) {
printf("%c\n", s[i] );
}
return 0;
}
the output I expect is something like s[] = {0,x,f,3}
This computation returns a char consisting of 4.
You are saying your computation returns a character which consists of 4 characters. Is it possible???
I guess your computation returns a string that consists of 4 characters. Example 0xf3
You can not store a string literal in char type variable.
char x = "0xf3"; //<---------------------
You can store them in a character array like char x[] = "0xf3";
Here is the modified code
#include <stdio.h>
#include<string.h> //<---- for strlen() and strcpy()
int main()
{
char x[] = "0xf3"; //<----store in a char array
char s[10];
strcpy(s, x); //<----copy in another array
int lingh = strlen(s);
for (int i = 0; i<lingh;i++) {
printf("%c\n", s[i] );
}
return 0;
}

Strange printf output in C

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char * reverse(char *string);
int main(int argc, char *argv[])
{
char array[10];
array[0] = 'a';
array[1] = 'b';
array[2] = 'c';
array[3] = 'd';
array[4] = 'e';
printf("1%s\n",array);
char *p = reverse(array);
printf("4%s\n",p);
printf("5%s\n",array);
}
char * reverse(char *string)
{
int size = strlen(string);
char reversed[size];
int i;
int j = 0;
for(i = size-1; i >= 0; i--)
{
reversed[j] = string[i];
j++;
}
printf("2%s\n",reversed);
string = reversed;
printf("3%s\n",string);
return reversed;
}
This code basically just initializes an array of values and passes it into a method that reverses these values.
I am not sure if this is the best way to execute the task, since I am new to pointers and arrays in C.
But the real question is this:
Can anyone figure out why in this line
printf("4%s\n",p);
if you remove the preceding '4', so it looks like so
printf("%s\n",p);
the line won't print at all?
You are returning a pointer to local variable(reversed) in the function reverse the question should actually be: Why did it work in the first place?.
This code string = reversed; will only copy the pointer, and again the local copy of the pointer so it has no effect outside the function.
To reverse a string you don't need additional memory - this can be done in-place.
Strings in C must end with the null character. You're using strlen on a non null-terminated string.
Furthermore, you just a very lucky person, because there is a serious problem with you code: you forget to add \0 symbol at the end of string.
UPD: the main problem is with code line char reversed[size];.
It's a regular local variable, it has automatic duration, which means that it springs into existence when the function is called and disappears when the function returns (see this link).
You need to change it to:
char *reversed = malloc((size+1)*sizeof(char));
UPD-2: another bug fixing will be:
1) add array[5] = '\0'; after all other array initializing lines
2) add reversed[j] = '\0'; after for...loop:
for(i = size-1; i >= 0; i--)
{
reversed[j] = string[i];
j++;
}
reversed[j] = '\0';
UPD-3: But in general it will much more correctly initialize your string in appropriate way:
char array[10] = "abcde";

C programming find length of 2 Dimensional array

My program grabs command line arguements with argc and argv[]. My question is how can I find the length of argv[1][i].
My code that grabs length of argv[]
int my_strlen(char input[]){
int len = 0;
while(input[len] != '\0'){
++len;
}
return len;
}
but when I try to find argv[1][len] I get a subscripted value is neither array nor pointer:
my attempt
int my_strlen(char input[]){
int len = 0;
while((input[1][len] - '0') != '\0'){
++len;
}
return len;
}
FULL CODE:
#include <stdio.h>
#include <math.h>
int my_strlen(char input[]);
int main(int argc, char *argv[]){
int length = 0;
length = my_strlen(argv[1]);
long numberArr[length];
int i, j;
for(i = 0; i < length; i++){
numberArr[i] = argv[1][i] - '0';
}
return 0;
}
int my_strlen(char input[]){
int len = 0;
while((input[1][len] - '0') != '\0'){
++len;
}
return len;
}
Thanks for any help in advance!
I think you're confused about the argv content. The OS will pass a number of ASCIIZ strings, such that invoking my_program with arguments ala...
my_program first second third
...is similar to having the following declaration in your program...
int argc = 4;
const char* argv[4] = { "my_program", "first", "second", "third" };
Hence, when you index into argv[1][i] you're getting the i-th character in the string "first". That's only valid for values of i between 0 (which yields 'f'), and 5 (which indexes to the terminating NUL character '\0').
So, there no two-dimensional N*M array, but there is an array of pointers-to-(array-of-char). You can invoke the normal strlen() function as in strlen(argv[1]) to find out the number of characters in each argument. Only argc tells you the total number of elements in argv.
Does that help?
In main, you're passing argv[1] to my_strlen. That means my_strlen just receives a normal, single-dimension string. It doesn't need to do input[1][len], just input[len].

Resources