How can I write C-program which accepts two strings from the user and prints a string which is the result of the concatenation of the first half of the two strings. For odd length strings, extra character goes in the first half of the string.
I have this so far but am confused on the splitting in half part...
printf("Please enter your first word.\n"); //Asks for first string
scanf("%s",&c); //Takes first string
printf("Please enter your second word.\n"); //Asks for second string
scanf("%s",&d); //Takes second string
strcat(c,d); //Combines both strings
If you just want to print out the result not caring about the content of the strings c and d any more you could do something like
#include <stdio.h>
#include <string.h>
int main(void) {
char c[1024]; // c string buffer
char d[1024]; // d string buffer
// initialize to empty strings
c[0] = '\0';
d[0] = '\0';
// read strings c and d
scanf("%s", c);
scanf("%s", d);
// just to make sure there is no overflow
c[1023] = '\0';
d[1023] = '\0';
// cut strings in middle
c[(strlen(c) + 1)/2] = '\0';
d[(strlen(d) + 1)/2] = '\0';
// print final string
printf("%s", c);
printf("%s\n", d);
return 0;
}
The result of (strlen(c) + 1)/2 does what you want because it performs an integer division. If strlen(c) gives an even size then adding 1 would make it the next odd with no effect on the integer division. If on the other hand the number is odd adding one will make it the next even achieving the rounding up you need. The '\0' will make sure that the string is terminated at that point.
If you don't want to loose the information of the two strings or need the resulting string stored then you could do something like
#include <stdio.h>
#include <string.h>
int main(void) {
char c[1024]; // c string buffer
char d[1024]; // d string buffer
char r[1024]; // resulting string buffer
int i; // general counter
int c_half_len; // c half length
int d_half_len; // d half length
// initialize to empty strings
c[0] = '\0';
d[0] = '\0';
r[0] = '\0';
// read strings c and d
scanf("%s", c);
scanf("%s", d);
// just to make sure there is no overflow
c[1023] = '\0';
d[1023] = '\0';
// get c and d half lengths rounding up
c_half_len = (strlen(c) + 1)/2;
d_half_len = (strlen(d) + 1)/2;
// copy first half c string to begining of result
for (i = 0; i < c_half_len; ++i) {
r[i] = c[i];
}
// copy first half d string after the end of the first half string
for (i = 0; i < d_half_len; ++i) {
r[c_half_len + i] = d[i];
}
// add an end of string character
r[c_half_len + d_half_len] = '\0';
// print final string
printf("%s\n", r);
return 0;
}
In both cases I assume that the two strings have a maximum length, in this case 1024 (including the end of string character). If that is not the case then you will need to handle things using dynamic memory.
void concathalf(const char *a, const char *b, char *out)
{
char *abuf, *bbuf;
if ((abuf = malloc(strlen(a) / 2)) && (bbuf = malloc(strlen(b) / 2))) {
memcpy(abuf, a, strlen(a) / 2);
memcpy(bbuf, b, strlen(b) / 2);
abuf[strlen(a) / 2] = bbuf[strlen(b) / 2] = 0;
}
sprintf(out, "%s%s", abuf, bbuf);
free(abuf);
free(bbuf);
}
Now, handling odd length inputs will be left as an exercise.
Related
So basically I'm trying to reverse a word (a single word, not a string with multiple words) and I've managed to reverse the word using this
{
int end, x;
end = strlen(myString) - 1;
for (x = end; x >= 0; --x) {
printf("%c", myString[x]);
}
}
(myString is defined somewhere else in the code)
But here's the kicker, I need to print the reversed word like this:
printf("The word reversed is '%c'", myString);
And I've no idea how to actually take the word reversed by the for loop and putting it into the second printf command. Any ideas?
Here you are.
for ( size_t i = 0, n = strlen( myString ); i < n / 2; i++ )
{
char c = myString[i];
myString[i] = myString[n - i - 1];
myString[n - i - 1] = c;
}
printf("The word reversed is '%s'\n", myString);
If the string you are passed is a literal instead of an allocated pointer, you'll need to make a reverse-copy of the string into an allocated buffer. Same applies if you are trying to avoid corrupting the orignial string.
// allocate a buffer big enough to hold a copy of the string
int len = strlen(myString);
char* reverse = malloc(len+1);
// reverse copy it over.
for (size_t i = 0; i < len; i++)
{
reverse[i] = myString[len-1-i];
}
reverse[len] = '\0'; // null terminate our new string
printf("Reversed word: %s\n", reverse);
// free the string when you are done with it
free(reverse);
I'm trying to write a run-length encoding program in C.
For the input 'ABBCD' I expect the following result: 'A1B2C1D1'
I hand over a two-dimensional char array line for line to the function that encodes the characters:
for(i; i <= curline; i++) //hand over line for line
{
encoded->lines[i] = malloc(255);
encoded->lines[i] = rle_encode(read->lines[i]); //read->lines contains the characters of each line
printf("%s", encoded->lines[i]); // print out the result returned by the function rle_encode
}
I have tested this and know that it would work.
Now this is my function rle_encode:
char *rle_encode(char *line){
char *encode = malloc(sizeof(2 * strlen(line) + 1));
char prev = line[0]; //here I want to save the previous character
int i = 0;
int z = 1;
do{
i++;
if(prev == line[i]) // if character n equals n-1 (previous)
{
z++; // increase counter varaible z
}else
{
strcat( encode, line[i] ); //the content of line[i] will be append to the array encode
strcat( encode, z ); //also the counter variable will be appended
}
prev = line[i];
}while(line[i] != '\n'); //in the end of each line a '\n' appears, if line[i] is '\n' it should stop the function
return encode;}
What is wrong in function rle_encode?
malloc(sizeof(encode))
sizeof(encode) is the size of a pointer, so you allocate for it only 4 or 8 bytes.
I think that you also have to start the counters i and z from 0, not from 1.
EDIT:
There are many problems, I did not mark them all.
This is not a complete answer to your question because there are many other issues in your code.
This small program shows how to append a char to a string and how to append the decimal representation of an int to a string.
#include <stdio.h>
#include <string.h>
int main(void)
{
char encode[100] = "abc";
printf("%s\n", encode);
// append the char 'X' to the encode string
int len = strlen(encode);
encode[len] = 'X';
encode[len + 1] = 0; // put the NUL terminator
printf("%s\n", encode);
// append the decimal representation of the int y to encode
int y = 123;
char *p = encode + strlen(encode);
sprintf(p, "%d", y);
printf("%s\n", encode);
}
Output:
abc
abcX
abcX123
You really need to learn the basics of C.
I need to call a c-function from matlab using y=coder.ceval() and return a string from the function. However the coder.ceval() function only allows me to return a scalar value. String is however an array of char, and thus cannot be returned. The code in matlab function looks like:
function y = abc(param)
y = '';
if strcmp(coder.target,'rtw'),
y=coder.ceval('c-function',param);
end
end
Is there any solution or workaround for it?
Looking forward for some help. Thank you very much!
EDITING
This is a workaround and you should use it at your own risk! ;)
I mean if it is really your last option.
As you do not specify the kind of string I assume for simplicity that it is composed only by uppercase letters (AABBBCC).
Uppercase letters are represented as decimal numbers by 2 digits (A = 65, Z = 90, man ascii).
This method comprises two steps:
1) In your function that you call via coder.ceval you should build a scalar value from the string you want to return. 2) You have to rebuild the string from the scalar value.
The following code illustrates by a simple example how to carry out the two steps. Keep in mind that is only an example and you have to work on it. Let's suppose for example that you need to return the string "ABC" then you can return the scalar "656667" which is composed by the three 2-digits numbers: 65=A, 66=B, 67=C.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
int i, len, n;
// First convert a string in a scalar value
char str[] = {'A', 'B', 'C', '\0'};
printf("str = %s\n", str);
len = strlen(str);
for (i = 0; i < len; i++) {
n = str[i] + i*100;
}
printf("n = %d\n", n);
// You return a scalar that is composed by 65,66,67 ---> A,B,C
int y = 656667;
char num[100];
char letter[3];
// convert the number in a string
snprintf(num, 100, "%d", y);
printf("num = %s\n", num);
len = strlen(num);
printf("num len = %d\n", len);
// here we assume that the number of digits id even only ascii letters
if ((len%2) != 0) exit(1);
// Now we have to store the number of two digits as numbers and
// then convert the to char and finally append tehm to a string
int *ni = malloc((len/2)*sizeof(int));
char *string = malloc(len + 1);
// Here I use a lot of intermediate steps to make it clear
char c = 0;
for (i = 0; i < len/2; i+=1) {
snprintf(letter, 3, "%c%c", num[2*i], num[2*i+1]);
ni[i] = atoi(letter);
c = (char)ni[i];
printf("letter %d = %s, x = %d, c = %c\n", i, letter, ni[i], c);
string[i] = c;
printf("string[%d] = %c\n", i, string[i]);
}
// print the final string
string[len] = '\0';
printf("string = %s\n", string);
return 0;
}
Lowercase letters starts at 97 but then become 3 digits, however by using some "special number" of 2 digits one can even decide to read 2 digits at the beginning of the string and 3 digits after the "special number".
Ok, I am not sure that this will help but, at least, I hope you find it interesting.
I'm trying to write a program which converts lower cased alphabet to numerical digits.
a -> 01
b -> 02
...
z -> 26
For the first nine letters I need to put a 0 before the number.
This is my code.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAXLEN 128
void s2n(char str[])
{
int i;
char x;
char result[256];
for (i=0; str[i] != '\0'; i++) {
x = str[i];
x = x - 96;
if (x < 10) {
char src[2] = {0, x};
strcat(result, src);
}
else {
char src2[1] = {x};
strcat(result, src2);
}
printf("%s", result);
}
}
int main(void)
{
char str[MAXLEN];
printf("Lower cased string please: ", MAXLEN);
scanf("%s", str);
s2n(str);
return 0;
}
Could you tell me what is wrong with my code??
One problem I see is:
char src[2] = {0, x};
You want to use the character 0, rather than the byte value 0 (NUL):
char src[2] = {'0', x};
Also, you need to NUL terminate your src array:
char src[] = {'0', x, 0};
The NUL termination would need to be done in both cases.
Another problem is your x = x - 96 statement also does not take into account that the character 0 is different from the byte value 0. So
x = x - 96 + '0';
would be better.
You use strcat() on an uninitialized array, result, it doesn't work that way, strcat() looks for the terminating nul byte in it's first parameter, and glues the second parameter from that point.
In your case there is no '\0' in result, calling strcat() with result as the first parameter causes undefined behavior.
You should at least ensure that there is one '\0' in result, you can do that by just setting the first element of result to '\0', like
result[0] = '\0';
Right before the loop starts, also you pass the second paramter src which is an array but is not a string, because it has no terminating '\0', but you actually don't need an array nor strcat().
You can use an index variable and just assing the ith element of the array to the actual character computed from the original value, like
result[i] = x;
Then you don't nul terminate result, which causes undefined behavior when you try to print resutl.
You also passing a parameter to printf() where it's not expecting one, that indicates that you are either silencing or ignoring compiler warnings.
There are many problems in your code, the following code, does what you want
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void s2n(char chr)
{
char result[4];
if (snprintf(result, sizeof(result), "%02d", 1 + chr - 'a') >= sizeof(result))
return;
printf("%s", result);
}
int main(void)
{
char chr;
printf("Lower cased string please: ");
if (scanf(" %c", &chr) != 1)
{
fprintf(stderr, "input error!\n");
return -1;
}
s2n(chr);
return 0;
}
note that no strings are required except the one where you are going to store the result, which you can build easily with sprintf().
I am trying to write a program that adds, subtracts, multiplies, and divides a string of characters. Where I'm at now with the program is figuring out how to split the input string into two strings, and then perform the appropriate +-/*.
The input should look like this abc+aaa
and the output for that should be abc + aaa = bcd
How do I convert character strings into integer strings?
#include <stdio.h>
#include <math.h>
#include <string.h>
int main() {
printf("This is a pseudo arithmetic program");
char input[10];
input[10] = '\0';
char first [9];
first[9] = '\0';
char last [9];
last[9] = '\0';
int i = 0;
int b;
int e;
while (input[0] != '0') {
if (input[0] == 0){
return -1;
}
printf("\nEnter a math problem in SOS format using only lowercase letters up to 9 characters");
printf("\nEx: abc+abc... type '0' to quit \n");
scanf("%s", input);
int x = 0;
x = strlen(input);
if (strchr(input, '+')){
for (i = 0; i <= x; i++) {
if (i == '+')
strncpy(first, &input[0], i-1);
i = 0;
}
for (i = x; i >= input[0]; i--) {
if (i == '+')
strncpy(last, &input[i], x);
i = 0;
}
printf("%s", first);
printf(" + ");
printf("%s", last);
printf(" = %d", first + last);
}
There seems to be multiple problems with your code:
There is a array out of bounds happening for almost all the arrays:
char input[10];
input[10] = '\0';
In this if you want to initialize the last character with '\0' then it should be
input [9] = '\0'
Arrays indexes always start from 0.
It is not clear what is the use of below lines:
while (input[0] != '0') { if (input[0] == 0){ return -1; }
When taking input for a string, why are prompting users to enter a 0 to end it?
strrchr returns the pointer from where the searched character begins. So, you can that itself to determine where the '+' symbol is and two split the strings instead of your while loop. See strrchr man page
Also, your idea of adding characters is not clear. From your example, it appears you are considering a = 1, b = 2 etc. In such a case, if your code is case insensitive, then you can convert all your input to upper case and then do (input[0] - 'A')+1 to convert your letters like a, b, c to 1, 2, 3 etc.
Hope these pointers help. Suggest you check your problem statement again and refactor your code accordingly.