Concatenate two characters in c - c

How to concatenate two characters and store the result in a variable?
For example, I have 3 characters 'a', 'b' and 'c' and I need to join them together and store them in an array and later use this array as a string:
#include <stdio.h>
#include <string.h>
char n[10];
main ()
{
// now I want insert them in an array
//ex: n = { a + b + c }
}

There are many ways, the following 2 methods have exactly the same results: (using your code as a starting point.)
#include <stdio.h>
#include <string.h>
int main(void)
{
//Given the following
char a = 'a';
char b = 'b';
char c = 'c';
// assignment by initializer list at time of creation
char n1[10] = {a,b,c};
//usage of a string function
char n2[10] = {0}; //initialize array
sprintf(n2, "%c%c%c", a, b, c);
return 0;
}
Both result in a null terminated char arrays, or C strings.

Simply:
char a = 'a', b = 'b', c = 'c';
char str[4];
str[0] = a;
str[1] = b;
str[2] = c;
str[3] = '\0';
Or, if you want str to be stored on the heap (e.g. if you plan on returning it from a function):
char *str = malloc(4);
str[0] = a;
...
Any introductory book on C should cover this.

An assignment similar to that can only be done when the char array is declared using array initialiation with a brace-enclosed list:
char a = 'a', b = 'b', c = 'c';
char n[10] = {a, b, c};
After the declaration you can't do it like this because a char array is not a modifiable lvalue:
n = {a, b, c}; //error
To insert characters in an array that has been previously initialized, you need to either insert them one by one as exemplified in another answer, or use some library function like sprintf.
sprintf(n, "%c%c%c", a, b, c);
In both of my examples the char array will be null terminated by the compiler so you can use it as a string, if you assign the characters one by one, make sure to place a null terminator at the end ('\0'), only then will you have a propper string.

Related

Why I cannot initialize an array with pointters?

I have tried to understand the connection between pointers and arrays. Why this prints "okkoD##"? Please help.
#include <stdio.h>
int main(){
char a = 'o';
char b = 'k';
char uga[2];
*(uga) = a;
*(uga+1) = b;
printf("%s", uga);
}
It is because a string in C is terminated by 0. So when you do this printf("%s", uga); the function will print the characters until it find the 0 element, then it stops. But there is none in uga, so it will keep printing characters from the stack. It is an undefined behavior. Try this
#include <stdio.h>
int main(){
char a = 'o';
char b = 'k';
char uga[3];
*(uga) = a;
*(uga+1) = b;
*(uga+2) = 0; // adding string terminating 0
printf("%s", uga);
}

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;
}

Insert char into char array C (string)

I got the char array "anana" and I am trying to get a "B" into the beginning in the char array so it spells "Banana" but I cannot wrap my head around how to construct a simple while loop to insert the B and then move every letter one step to the right
Assuming:
char array[7] = "anana";
Then:
memmove(array+1, array, 6);
array[0] = 'B';
The memmove function is specifically for cases where the data movement involves an overlap.
You can use a more traditional approach using...
#include <stdio.h>
int main()
{
char s[] = "ananas";
char b[7] = "B";
for(int i = 0; i < 7; ) {
char temp = s[i++];
b[i] = temp;
}
printf("%s", b);
return 0;
}
Please follow these steps:
Create a new array of size 7 (Banana + terminator). You may do this dynamically by finding the size of the input string using strlen().
Place your desired character say 'B' at newArray[0].
Loop over i=1 -> 7
Copy values as newArray[i] = oldArray[i-1];

Add two int chars together into one char array or string

How can i add Add two int chars together into one char array or string like :
char *s;
int a = 'A';
int b = 'B';
s = a + b;
the terminal givs me :
incompatible integer to pointer conversion assigning to 'char *' from
'int'
Have a look at sprintf to print the values to a string.
char my_cstring[32] = "";
char a = 'A';
char b = 'B';
sprintf(my_cstring, "%c%c", a, b);
// output: "AB"

Compare char arrays

If I had an array of characters for example:
A = [w, o, r, n, g, , w, o, r, d]
And another array for example:
B = [c, o, r, r, e, c, t, , w, o, r, d, .]
I need to compare the words in array A (which are separated by a blank space) to array B and if any of the words in the first array exist in the second array, then that word should be printed. So for example, since "word" exists in the first array and in the second array, then "word" should be printed out.
How do I go about this?
Let's see how I would do it:
You will need a function that, given an array of char, splits it in an array of words (and put them in C strings, NUL terminated please :-) ). I would put the length of this array and the array in a struct
struct WordCollection
{
size_t NumWords;
char **Words;
}
Now... How to do this function?
Let's say we "cheat" a little and decide that our arrays A and B are NUL terminated (or if they are . terminated like B, then you replace the . with a NUL). Now, this being C, you should first count the number of spaces in the string, allocate an array of char* (WordCollection::Words) big enough to contain n + 1 char* (and put this n + 1 in WordCollection::NumWords) and using strtok "tokenize" the string and put the words in the array you created.
Then you should (could) split the A and B array in words using this function. You'll obtain two WordCollection, A1 and B1.
To make it quicker, I would qsort B1.
Then for each word in A1 you bsearch it in B1 (it isn't a bad word... It means Binary Search, and it's a quick method of searching something in an ordered array)
Done :-)
I'll add that, if this is the first time you use bsearch and qsort, it's better you look at the samples you can find around. Their syntax can be "tricky".
Now... I know you won't look at the code :-) so I'll put it here
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct WordCollection
{
size_t NumWords;
char **Words;
};
void splitWord(char *str, struct WordCollection *wc)
{
char *c;
char **currentWord;
c = str;
wc->NumWords = 1;
while (*c != '.')
{
if (*c == ' ')
{
wc->NumWords++;
}
c++;
}
*c = '\0';
wc->Words = (char**)malloc(wc->NumWords * sizeof(char*));
c = strtok(str, " ");
currentWord = wc->Words;
while (c)
{
*currentWord = c;
currentWord++;
c = strtok(NULL, " ");
}
}
int myComp(const void *p1, const void *p2)
{
return strcmp(*(const char**)p1, *(const char**)p2);
}
int main(void)
{
char a[] = { 'w', 'o', 'r', 'n', 'g', ' ', 'w', 'o', 'r', 'd', '.' };
char b[] = { 'c', 'o', 'r', 'r', 'e', 'c', 't', ' ', 'w', 'o', 'r', 'd', '.' };
struct WordCollection a1, b1;
struct WordCollection *pSmaller, *pBigger;
size_t i;
splitWord(a, &a1);
splitWord(b, &b1);
if (a1.NumWords <= b1.NumWords)
{
pSmaller = &a1;
pBigger = &b1;
}
else
{
pSmaller = &b1;
pBigger = &a1;
}
qsort(pBigger->Words, pBigger->NumWords, sizeof(char*), myComp);
for (i = 0; i < pSmaller->NumWords; i++)
{
void *res = bsearch(&pSmaller->Words[i], pBigger->Words, pBigger->NumWords, sizeof(char*), myComp);
if (res)
{
printf("Found: %s", pSmaller->Words[i]);
}
}
free(a1.Words);
free(b1.Words);
return 0;
}
And on ideone
Basically you need to somehow separate the words, and then iterate through the combinations. There are a hundred ways to do this -- it simply requires programming.
You can also do it like that:
Insert all words from set A into set C with suffix 'A'. You will get =>
worngAwordA
Insert all words from set B into set C with suffix 'B'. You will get =>
correctBwordB
Run sorting algo on set C such as qsort. You will get =>
correctBwordAwordBworngA
Loop in set C until it's size-1. Compare word[i] with word[i+1] - if they match except the last letter - you found duplicate and you can print it out.
I don't know about this algorithm complexity, but it clearly should be faster than just brute-force scan of all words combinations :-)

Resources