I have the following C Code
#include <stdio.h>
int main(void){
char c[] = "ABC"
printf("%s ", c);
c[1] = 'B';
printf("%s", c);
return 0;
}
The output I want is ABC BBC but the output I get is ABC ABC. How can I replace the first character in an String / char array?
Indexing in C arrays start from 0. So you have to replace c[1] = 'B' with c[0] = 'B'.
Also, see similar question from today: Smiles in output C++ - I've put a more detailed description there :)
Below is a code that ACTUALLY WORKS!
char * replace_char(char * input, char find, char replace)
{
char * output = (char*)malloc(strlen(input));
for (int i = 0; i < strlen(input); i++)
{
if (input[i] == find) output[i] = replace;
else output[i] = input[i];
}
output[strlen(input)] = '\0';
return output;
}
C arrays are zero base. The first element of the array is in the zero'th position.
c[0] = 'B';
try
c[0] = 'B';
arrays start at 0
Related
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];
I want to read the following lines from STDIN and save the values in c:
A:2
B:3
C:AAAA1
C:AASC2
C:aade3
D:1
D:199
Here is my c program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <time.h>
#include <sys/time.h>
int main(int argc, char **argv)
{
char buf[BUFSIZ];
short a = 0;
short b = 0;
short anzb=0;
short anza=0;
char *c
short *d;
short i;
while (fgets(buf, BUFSIZ, stdin) != NULL)
{
if (buf[strlen(buf)-1] == '\n') {
char *isa = strstr(buf, "A:");
char *isb = strstr(buf, "B:");
char *isc = strstr(buf, "C:");
char *isd = strstr(buf, "D:");
if(isa){
char *sep = substring(isa,3,strlen(isa));
a = atoi(sep);
d = malloc(a * sizeof(short));
}else if(isb){
char *sep = substring(isb,3,strlen(isb));
b = atoi(sep);
c = malloc(b * sizeof(char));
}else if(isc){
char *sep = substring(isc,3,strlen(isc));
c[anzc] = sep;
anzc++;
}else if(isd){
char *sep = substring(isd,3,strlen(isd));
d[anzd] = sep;
anzd++;
}
}
}
printf("%i\n", a);
printf("%i\n", b);
for(i=0; i<=anzc-1;i++){
printf("%c", c[i]);
}
return 0;
}
I am new in c so i dont't have much knowledge about pointers and arrays so i hope you could help me.
After the values A: and B: are read and stored in a and b i could create my array for the lines of c and d. And i think here is my problem. I dont know how i could create an array at this time in my program. I tried with malloc and other things but there is my knowledge zu small for.
I only want to create an array at the time if i have read the values (sizes) for c and d (A and B).
And then i want to save the values in the array.
I hope you could help me to fix my code. I have tried much at this day but nothing worked and i am now very helpless.
EDIT:
New try where i get an segmentation fault 11:
else if(isb){
char *sep = substring(isb,8,strlen(isb));
b = atoi(sep);
c = malloc(b * sizeof(char*));
int i;
for (i = 0; i < subst; i++)
{
c[i] = malloc(13);
}
}else if(isc){
char *sep = substring(isc,8,strlen(isc));
strcpy(c[anzc], &buf[3]);
anzc++;
}
Your allocation is more or less correct however you're overlooking some details. B provides you a value of 3, that is how many entries there are for C, not the length of each. You then allocated a single array when you in fact need a 2-D array which should be of type char* this array will point to 3 other arrays which will contain each of the values on the C lines. So;
This line c = malloc(b * sizeof(char)); needs to be c = malloc(b * sizeof(char*));
Then you need to do;
int i;
for (i = 0; i < b; i++)
{
c[i] = malloc(length); // where length is some arbitrary buffer length
// because you have no way of knowing the length of the individual strings.
}
After this you can use strcpy to copy the lines into each of the char arrays you've allocated in the for loop.
So to accomplish the copy you need to do something like this;
int iC = 0;
// outside of the while loop we need a control var track the index
// of the c array. it needs to work independent of the normal iteration.
//inside the while loop
else if(isc){
strcpy(c[iC], &buf[3])
iC++;
}
#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";
how to store Ascii character a to z in any one type of variable using strcpy?
for(i=97;i<122;i++)
{
for(j=97;j<122;j++)
{
printf("%c%c",i,j);
int a = strcpy(i,j);
}
}
char a[3] = {0};
for(i=97;i<122;i++)
{
for(j=97;j<122;j++)
{
printf("%c%c\n", i, j);
a[0] = i;
a[1] = j;
printf("%s\n", a);
}
}
So (assuming ASCII):
char str[27]={0};
char temp[2]={0};
int i;
for (i='a';i<='z';i++) {
temp[0]=i;
strcpy(str,temp);
}
But do you really need to use strcpy?
Ηow to store Ascii character in any one type of variable using strcpy()?
You don't need it, since for a single character strcpy() is unnecessary.
Moreover, you try to handle an int with strcpy(), whereas this function handles char*.
What you could do is something like this:
char myarray[3] = {0};
for(i = 97; i < 122; i++)
{
for(j = 97; j < 122; j++)
{
printf("%c%c\n", i, j);
myarray[0] = i;
myarray[1] = j;
printf("%s\n", myarray);
}
}
where I used a char array, since if you store the ASCII character in an int you cannot expect it to print the same character, as it was stored in a char. Even if you try Convert char array to a int number in C, you will not be able to succeed in it.
you can do it easily using type cast inside your loop
int num = 97;
char a = (char)num; // 'a' = 97 casting int to char
num = (int)a // num = 97 cast 'a' to ASCII
let it try
int main() {
int a = 0;
char c = '\0';
scanf(" %c", &c);
a = c + 0;
printf("%d", a);
}
Output: ASCII value of entered character.
I have provided the the code. Please refere it.
Why this is So?
Focus on the addition operation which is assigned to the int variable a. During compilation of this operation compiler finds that the variable c is of char type but; the operator + is next to it and hence compiler uses the ascii value of the character stored in c variable.
I hope it will helpful for you. Thank you.
My head is getting bad trying to find a solution for this assignment because my ideas didn't work...
I have to interlace two char strings using pointers. See the following example (this example is not code):
char s1 = "My House Black"
char s2 = "Are very near"
Result: "MAyr eH ovuesrey Bnleaacrk"
How can I do this?
Try:
int total = strlen(char1) + strlen(char2);
int i1 = 0, i2 = 0;
for(i = 0; i < total; i++)
{
if(i % 2 == 0)
{
result[i] = char1[i1];
i1++;
}
else
{
result[i] = char2[i2];
i2++;
}
}
Here's a hint (pseudocode):
result = ""
for i = 0 to longest string's length:
result += some character (whose?)
result += another character (also, whose?)
Be careful: you need a little check somewhere, otherwise bad things might happen.
Since this is homework, I will just give you an outline.
First of all declare your two strings:
const char *s1 = "My House Black";
const char *s2 = "Are very near";
Next declare two pointers to char:
char *p1 = s1;
char *p2 = s2;
Now enter a while loop. The condition should be that *p1 or *p2 are not equal to zero.
Inside the loop output *p1 if it is not zero and then output *p2 if it is not zero. Increment each pointer if it refers to a non-zero character.
That's it, you are done!
Since this is tagged homework, I don't want to directly post code. But create three character arrays, one for each input, one long enough to contain the output, and traverse the input character arrays one character at a time (use pointer arithmetic). Store the character into your output string. Continue until you reach the end of each string. Don't forget the null terminations!
You need a target string that is large enough to hold both input strings and the string terminator.
Then you should probably use a loop (while or for) where you copy one character from each input string in each iteration.
For extra credits:
Consider the case where the input strings are of unequal length.
Is this what you want?
char * s1 = "My House Black";
char * s2 = "Are very near";
char * s = (char *)malloc(strlen(s1) + strlen(s2) + 1);
char * p1 = s1;
char * p2 = s2;
char * p = s;
while (*p1 && *p2)
{
*p++ = *p1++;
*p++ = *p2++;
}
while (*p1)
{
*p++ = *p1++;
}
while (*p2)
{
*p++ = *p2++;
}
*p = '\0';