#include<stdio.h>
#include<string.h>
int main()
{
char c='g';
char d[]="John ";
strcat(d,&c);
puts(d);
return 0;
}
The output is:
John gC
The 'C' wasn't required.
Also, what does const char* mean here?
char *strcat(char *dest, const char *src)
Also, is a statement like this (inside a loop) wrong somewhere if I wish to add a character at the end of string?
char arr[]=' ';
symb[]={'a','b','c'}
strcat(arr, &symb[k]);
k++;
You are writing out of the bounds of d, you need room for one more char, change to
char d[7] = "John ";
or (if you don't want to specify the size of the array):
char d[] = "John \0";
or
char d[] = {'J', 'o', 'h', 'n', ' ', '\0', '\0'};
Also strcat wants a valid NUL terminated string and you are passing a pointer to a single char, change to
char *c= "g";
Two ways(there are even more):-
1>
char *c="g";
char d[10]="John ";
strcat(d,c);
2>
char c[]="g";
char d[10]="John ";
strcat(d,c);
Though I advise d[10] = {0} ; and then copy the string. (as David mentioned in comments.)
You need to learn the basics of C and C-style strings. Specifically, that a special zero-value character identifies the end of the string.
You have copied over the string but you did not copy the terminator. Therefore, functions like puts() don't know when to stop and print other characters that happen to be in memory.
There is undefined behaviour in your program . strcat requires null terminated string as its arguments where c is not . You can do this-
char c[]="g";
char d[7]="John "; // leave space for 'g' as well as for '\0'
strcat(d,c); // then pass both to strcat
Another way is to use sprintf -
char c[]="g";
char d[10]="John";
size_t n =strlen(d);
sprintf(&d[n]," %s",c);
This works: ( if you wanted John g )
#include<stdio.h>
#include<string.h>
int main()
{
char c='g';
char d[10];
char temp[2];
strcpy(d ,"John ");
temp[0]=c;
temp[1]='\0';
strcat( d , temp );
puts(d);
return 0;
}
This works: ( if you wanted Johng )
#include<stdio.h>
#include<string.h>
int main()
{
char c='g';
char d[]="John ";
//strcat(d,&c);
d[strlen(d)-1]=c;
puts(d);
return 0;
}
Related
This is my code. I am trying to simulate strcpy(). This code works, but I have a couple questions.
#include <stdio.h>
#include <stdlib.h>
char *strcpy(char *d, const char *s);
int main()
{
char strOne[] = "Welcome to the world of programming!";
char strTwo[] = "Hello world!";
printf("String One: %s\n", strOne);
printf("String Two before strcpy(): %s\n", strTwo);
strcpy(strTwo, strOne);
printf("String Two after strcpy(): %s\n", strTwo);
return 0;
}
char *strcpy(char *d, const char *s)
{
while (*s)
{
*d = *s;
d++;
s++;
}
*d = 0;
return 0;
}
When *s gets incremented to the position where '\0' is stored in the array, is that when the while condition becomes false because of '\0'? Does while read '\0' or just '0'?
'while' condition will be true if it reads '1'. All previous values of *s should be read as single characters in while condition, but the loop executes anyways. Why does this happen? Do all the single characters from the array *s is pointing equate to the value '1'?
What does *d = 0; exactly do? The way I understand it, the copying process is completed when the while loop is exited. So why does removing *d = 0 lead to an incorrect output being displayed?
Output without *d = 0 :
String Two before strcpy(): Hello world!
String Two after strcpy(): Welcome to the world of programming! programming!
Output with *d = 0 :
String Two before strcpy(): Hello world!
String Two after strcpy(): Welcome to the world of programming!
The characters in the ASCII table assume values that range from 0 to 127, 0 being NULL or '\0', so the condition is always true unless the character is '\0'.
*d = 0 places a '\0' at the end of the string; it's how strings are terminated in C. If you don't terminate the string, anything can be printed past the end of the string, and the program has no way to know where it ends. It's undefined behaviour.
Some more remarks. You return 0 instead of pointer to char. You should get some warnings. Return the copy instead. BTW this function can be simplified a bit as well.
char *strcpy(char *d, const char *s)
{
char *saved = d;
while ((*d++ = *s++));
return saved;
}
I am currently trying to handle string in C and I am having trouble placing the split values of a string into an array. Bellow is the code I have created in an attempt to achieve this.
#include <stdio.h>
#include <string.h>
int main(){
char str[]="titanic.txt";
char parts[2][5];
char *name = strtok(str, ".");
for (int i = 0; i < 2; i++){
parts[i][5] = name;
char name = strtok(NULL, ".");
}
printf("%c\n", str[0]);
return 0;
}
The output I would be expecting from this would hopefully look something like this.
char part[2][10]{
{'t', 'i', 't', 'a', 'n', 'i', 'c'},
{'t', 'x', 't'}
};
alternatively, I have tried something like this using string copy as such.
#include <stdio.h>
#include <string.h>
int main(){
char str[]="titanic.txt";
char parts[2][10];
char *name = strtok(str, ".");
for (int i = 0; i < 2; i++){
strcpy(parts[i], name);
name = strtok(NULL, ".");
}
printf("%s\n", parts[1]);
return 0;
}
Which, did what I want it to, but I would like to try and achieve this without string copy because I feel it will help me understand strings, characters, and arrays better. I do not want to reinvent the wheel I just want a deeper understanding.
The parts array should be an array of pointers, not a 2-dimensional array of characters:
char *parts[2];
Then you assign:
parts[i] = name;
If you want to copy from the input string to parts, you need to declare the 2nd dimension large enough for the largest possible string:
char parts[2][10];
and then you should use strcpy() rather than assignment to copy it.
strcpy(parts[i], name);
Notice that you don't give a second index to parts when doing this, that's only used to access specific characters of the string, not the string as a whole.
In case separating a file name from its extension is actually relevant to whatever you're trying to accomplish, I'll assume you're using Windows and point you to the documentation for the recommended Windows API library for this, <pathcch.h>.
With regard to your actual question, your first code doesn't work because:
You're assigning to a single character in the line parts[i][5] = name;. You're also overflowing since parts[i] has the type char [5], which only has positions 0 to 4.
You redeclare name as a single char rather than a char * pointer, which is the correct type, and was declared as such (correctly) outside the loop scope. Your new variable char name overwrites the existing char *name variable.
You cannot get around using strcpy-family functions to assign to a character array for this (and most other) use cases. The only time the syntax char foo[] = "Hello World"; is valid is immediately on declaration. Also, string literals are stored in read-only memory.
Following your coding style, this is the solution:
#include <stdio.h>
#include <string.h>
int main()
{
char str[] = "titanic.txt";
char delim[] = ".";
char parts[2][10];
char *ptr = strtok(str, delim);
int i = 0;
for (i = 0; i < 2; i++){
if(ptr != NULL)
{
snprintf(parts[i], sizeof(parts[0]) ,"%s", ptr);
ptr = strtok(NULL, delim);
}
}
printf("'%s'\n", parts[0]);
printf("'%s'\n", parts[1]);
return 0;
}
#include <stdio.h>
void reverse(int len, char s[], char b[]);
int main() {
char s[5] = "hello";
char b[5];
reverse(5, s, b);
return 0;
}
void reverse(int len, char s[], char b[]) {
int i;
for (i = 0; i < len; i++) {
b[(len - 1) - i] = s[i];
}
printf("%s : %s\n", s, b);
printf("%s", b);
}
Here is my code above in C. When I run it, it switches the string s[] to b[] but b[]also includes s[]. Can someone please thoroughly explain what I'm doing wrong? I really appreciate it.
char s[5] = "hello";
This is wrong, you need one more [6] in order to store the trailing '\0' (same for b)
It's better to omit the array size:
char s[] = "hello";
char b[sizeof(s)];
And you need b[i] = '\0'; after the for loop.
Your string buffers are too small, they must be six characters or more to hold the string "hello". Remember that strings C have a terminating '\0'-character at the end; that won't fit with space for only five characters.
Also, when reversing you never copy the terminating character.
You need b[len - 1] = '\0'; before exiting reverse().
When you pass non-terminated strings to printf()'s "%s" format, you get undefined behavior. Typically it "runs off the end" of the string, printing whatever it happens to find in memory, until it finds a character with the value 0 which causes it to stop.
The %s format specifier expects a string: An array of characters ending in a nul byte. You are not supplying that, so you are getting rubbish results. To hold a string with five characters, you need at least six chars.
every string in c is terminated by \0 which is a null character. so the array size should be enough to hold the string along with null character.
I will suggests to increase the size of array.
important :-
at the last assign b[last_index]='\0';
so that string b can be terminated by \0. otherwise it might give garbage values along with actual data while printing the string b.
In C, you just need to include
#include<string.h>
and use
strrev(a);
where a is the character array or string.
Whereas, your code can be modified too, to be written like this
#include <stdio.h>
void reverse(int len, char s[], char b[]);
int main() {
char s[5] = "hello";
char b[5];
reverse(5, s, b);
return 0;
}
void reverse(int len, char s[], char b[]) {
int i,j;
for (i = 0,j=len-1; i <=j; i++, j--) {
b[j]=a[i];
}
printf("%s : %s\n", s, b);
printf("%s", b);
}
I wanted to write a code which makes a uppercase of first letter of string 1 and 3 and printing those.
I tried the code below this but compiler gives İNVALİD CONVERSİON OF CHAR TO İNT
What is wrong with this code should i try with strlen and for loop?
This is code;
int main()
{
char str1[] = "elektrik";
char str2[] = "ve";
char str3[] = "elektronik";
str1 = toupper(str1);
str3 = toupper(str3);
printf("%s %s %s",str1,str2,str3);
getch();
return 0;
}
You need
*str1 = toupper(*str1);
...
Asssuming that str1 is a pointer to char (and include the appropriate header files)
/* strchr example */
#include <stdio.h>
#include <string.h>
int main ()
{
char str[] = "This is a sample string";
char * pch;
printf ("Looking for the 's' character in \"%s\"...\n",str);
pch=strchr(str,'s');
while (pch!=NULL)
{
printf ("found at %d\n",pch-str+1);
pch=strchr(pch+1,'s');
}
return 0;
}
How would I index the str so that I would replace every 's' with 'r'.
Thanks.
You don't need to index the string. You have a pointer to the character you want to change, so assign via the pointer:
*pch = 'r';
In general, though, you index using []:
ptrdiff_t idx = pch - str;
assert(str[idx] == 's');
You can use the following function:
char *chngChar (char *str, char oldChar, char newChar) {
char *strPtr = str;
while ((strPtr = strchr (strPtr, oldChar)) != NULL)
*strPtr++ = newChar;
return str;
}
It simply runs through the string looking for the specific character and replaces it with the new character. Each time through (as with yours), it starts with the address one beyond the previous character so as to not recheck characters that have already been checked.
It also returns the address of the string, a trick often used so that you can use the return value as well, such as with:
printf ("%s\n", chngChar (myName, 'p', 'P'));
void reeplachar(char *buff, char old, char neo){
char *ptr;
for(;;){
ptr = strchr(buff, old);
if(ptr==NULL) break;
buff[(int)(ptr-buff)]=neo;
}
return;
}
Usage:
reeplachar(str,'s','r');
Provided that your program does really search the positions without fault (I didn't check), your question would be how do I change the contents of an object to which my pointer pch is already pointing?