I need to build a function in C, that receives two strings str1 and str2 and returns a string that is the concatenation str1 and str2, but I need to discard the last elements of str1 that are equal to the first elements of str2.
Example 1:
str1 = ccabcc
str2 = ccbabd
result : ccabccbabd
Example 2:
str1 = abbcbf
str2 = ab
Result : abbcbfab
Sometimes there is no overlapping.
This problem is trivial imho. Personally, I would go with something like this(it is pseudo code):
function(str1,str2)
int j = 0
int lstr1 = lenght of str 1
int lstr2 = lenght of str 2
while(true)
if(str1[lstr1 - j] == str2[j])
j++
else
break
return str1 + str2[j to end of string]
If I did not make logic mistake, you code should look like something that compare the end of str 1 to beginning of str 2 and increment. Also, my pseudo code don't take into account the string lenght and potential overflow error.
I hope this is what you need:
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
char *concate(char *first, char *second){
size_t len1 = strlen(first);
size_t len2 = strlen(second);
char *res = (char *)malloc(len1 +len2 +1);
if(res==NULL){
exit(1);
}
if(first[len1-1] == second[0]){
first[len1-1] = 0;
second++;
}
strcpy(res,first);
strcat(res,second);
return res;
}
int main(void){
int i = 0,len = 0;
char arr[] = "ccabcc";
char arr2[] = "ccbabd";
char *res = concate(arr,arr2);
while(res[len] != '\0'){
len++;
}
for(i=0;i<len;i++){
printf("%c",res[i]);
}
printf("\n");
free(res);
return 0;
}
Output:
ccabccbabd
int main(){
char a[256], b[256];
printf("Enter 1st string\n");
gets(a);
printf("Enter the 2nd string\n");
gets(b);
strcat(a,b);
printf("String concatenation is %s\n",a);
}
Related
I'm trying to reverse a string using pointers sptr1 and sptr2, The len gives the correct length of the entered string but the string is not reversed and str1 is not displaying on my terminal. Please provide some insights
#include<stdio.h>
void main()
{
char str1[10];
char temp;
char *sptr1;
char *sptr2;
int len;
printf("Enter a string:");
scanf("%s",&str1);
sptr1=str1;
sptr2=str1;
while(*sptr1!='\0')
{
sptr1++;
}
len=sptr1-str1;
printf("Length of the string:%d",len);
while(len!=0)
{
temp=*sptr1;
*sptr1=*sptr2;
*sptr2=temp;
sptr1--;
sptr2++;
len=len-1;
}
printf("%s",str1);
}
After while(*sptr1!='\0')... sptr points to the null-terminator of the string and then you are switching this null terminator with the first character. E.g. you move the null terminator to index 0. You have to decrement sptr before starting the reverse.
You should also decrement len by 2, otherwise you would iterate over the whole array and switch the already switched characters back.
Some other small mistakes:
main should return int, not void.
scanf("%s", &str1); should be scanf("%s", str1);, str1 already decays to a pointer.
You should add \n in your printf statements to have the output in different lines instead of 1 long line.
#include<stdio.h>
int main() {
char str1[10];
char temp;
char *sptr1;
char *sptr2;
int len;
printf("Enter a string:\n");
scanf("%s", str1);
sptr1 = str1;
sptr2 = str1;
while ( *sptr1 != '\0') {
sptr1++;
}
len = sptr1 - str1;
printf("Length of the string:%d\n", len);
sptr1--;
while (len > 0) {
temp = *sptr1;
*sptr1 = *sptr2;
*sptr2 = temp;
sptr1--;
sptr2++;
len = len-2;
}
printf("%s\n", str1);
}
See it live: https://ideone.com/WAnQLi
#include<stdio.h>
#include<string.h>
int main(int argc, const char * argv[])
{
char s[]="hello";
strrev(s);
puts(s);
return 0;
}
try strrev function:
char *strrev(char *str);
there is only one mistake #mch's code in
len = len - 2;
because of this, program won’t work for string which length is even number correctly.
I write to code because of more readability.
#include <stdio.h>
int main()
{
char str[10];
printf("Enter a string:\n");
scanf("%s", str);
char *ptr1, *ptr2;
ptr1 = ptr2 = str;
size_t len = 0;
while (*ptr1) {
++ptr1, ++len;
}
printf("Length of the string:%u\n", len);
for (int k = 0; k < len / 2; ++k) {
char temp = *(--ptr1);
*ptr1 = *ptr2;
*ptr2++ = temp;
}
printf("%s\n", str);
}
Just an additional answer, be very careful with buffer overflow issues. Also a minor detail, you don't really need a len variable.
Below a commented code showing a way to deal carefully with memory writing.
#include <stdio.h>
// Here a way to use constants both as integer and strings
// See https://stackoverflow.com/questions/5459868
#define STR_HELPER(x) #x
#define STR(x) STR_HELPER(x)
// Let's define a max length
#define MAX_STRING_LENGTH 10
void main()
{
char sptr[MAX_STRING_LENGTH + 1];
char *sptr1=sptr,*sptr2=sptr;
char swap;
printf("Enter a string (" STR(MAX_STRING_LENGTH) " at most): ");
// Here, limit the input to sptr size - 1
// (let the last index for the null character)
// Example : "%10s" means "at most 10 characters, additional ones
// will be removed."
scanf("%" STR(MAX_STRING_LENGTH) "s",&sptr);
// Finding the last character BEFORE the NULL character
while(*(sptr2+1) != '\0') sptr2++;
// Swaping
while (sptr2 > sptr1)
{
printf("\t-> swaping %c <-> %c\n", *sptr1, *sptr2);
swap=*sptr1;
*sptr1=*sptr2;
*sptr2=swap;
sptr1++,sptr2--;
}
printf("Result : [%s]\n",sptr);
}
Examples (strings with odd and even length):
user:~$ ./a.out
Enter a string (10 at most): abc
-> swaping a <-> c
Result : [cba]
user:~$ ./a.out
Enter a string (10 at most): abcd
-> swaping a <-> d
-> swaping b <-> c
Result : [dcba]
user:~$ ./a.out
Enter a string (10 at most): abcdefghijklmnopqrstuvwxyz
-> swaping a <-> j
-> swaping b <-> i
-> swaping c <-> h
-> swaping d <-> g
-> swaping e <-> f
Result : [jihgfedcba]
I have the following program that I want to read in my name (Sahand) character by character and store in a string:
#include <stdio.h>
int main(int argc, const char * argv[]) {
char temp;
char str[6];
int i;
for ( i = 0 ; i < 6 ; i++ )
{
scanf(" %c",&temp);
printf("Our temp is: %c\n",temp);
str[i] = temp;
printf("Our total string is: %s\n",str);
}
printf("Program ended with the string: %s\n",str);
return 0;
}
The output is this:
s
Our temp is: s
Our total string is: s
a
Our temp is: a
Our total string is: sa
h
Our temp is: h
Our total string is: sah
a
Our temp is: a
Our total string is: saha
n
Our temp is: n
Our total string is: sahan
d
Our temp is: d
Our total string is: sahandd\350\367\277_\377
Program ended with the string: sahandd\350\367\277_\377
Program ended with exit code: 0
As you can see, everything is going fine until the final letter, d, is entered, when another d and a bunch of random stuff is added onto the string. Could someone explain to me what is happening here?
You should be adding the null character to the string before printing. Since you're printing inside a loop, add it to the next character. Just absolutely be sure that the for loop doesn't go beyond the bounds of the array.
#include <stdio.h>
int main(int argc, const char * argv[]) {
char temp;
char str[7];
int i;
for ( i = 0 ; i < 6 ; i++ )
{
scanf(" %c",&temp);
printf("Our temp is: %c\n",temp);
str[i] = temp;
str[i+1] = '\0';
printf("Our total string is: %s\n",str);
}
printf("Program ended with the string: %s\n",str);
return 0;
}
Another option is to actually initialize each character in the C-String to be the '\0' character (without ever overwriting the last one); As some others have mentioned in the comments, this can be accomplished in the declaration of the array as such:
char str[7] = { 0 };
You need null character('\0') to end your string(array) at the 5th index in order to tell the compiler that this is the end of string(in your case character array i.e., str). But you were using 5th index to store character 'd'.
The compiler is taking garbage value from the memory
In order to run your program correctly, you need to declare the str array as below:
char str[7];
And insert null character('\0') at (i+1)th position.Look below:
#include <stdio.h>
int main(int argc, const char * argv[]) {
char temp;
char str[7];
int i;
for ( i = 0 ; i < 6 ; i++ )
{
scanf(" %c",&temp);
printf("Our temp is: %c\n",temp);
str[i] = temp;
str[i+1] = '\0';
printf("Our total string is: %s\n",str);
}
printf("Program ended with the string: %s\n",str);
return 0;
}
After reading the comments, I changed the following line in my program:
char str[6];
to
char str[7];
That did the trick and the program executes as I wish.
EDIT:
In addition to changing this line, I added a str[6] = 0; after the variable declaration.
Here is a simple code of reversing the string in C the last printf statement prints the reverse order , but with a question mark at the end, while I just want to print the reversed string not the question mark
How do I fix it?
#include<stdio.h>
#include<string.h>
int main(){
char new_string[100];
char string[100];
scanf("%s",string);
printf("original_number = %s\n",string);
int i;
int l = strlen(string)-1;
for(i = 0; i<=l; i++){
new_string[i] = string[l-i];
printf("%c\n",new_string[i]);
}
printf("rev_number = %s\n",new_string);
}
input : abcd
output:
original_number = abcd
d
c
b
a
rev_number = dcba?
You need to null terminate your string.
Add this line at after the for loop where you reverse string.
new_string[i]='\0';
for(i = 0; i<=l; i++){
new_string[i] = string[l-i];
printf("%c\n",new_string[i]);
}
new_string[i]='\0'; // add this
printf("rev_number = %s\n",new_string);
check-here
terminate new_string by new_string[i]='\0' after for-loop
If the question is "How to add '?' to the end of string?" I have to answers:
1) use strcat to add one more character, e.g.:
#include<stdio.h>
#include<string.h>
int main(){
char new_string[101] = {0}; // +1 to be sure that enough place for '?' will be available
// {0} to init empty string
char string[100];
scanf("%s", string);
printf("original_number = %s\n", string);
int i;
int l = strlen(string) - 1;
for (i = 0; i <= l; i++){
new_string[i] = string[l - i];
printf("%c\n", new_string[i]);
}
strcat(new_string, "?");
printf("rev_number = %s\n", new_string);
}
2) put ? and add character \0 after the loop end, e.g.:
#include<stdio.h>
#include<string.h>
int main(){
char new_string[101]; // +1 to be sure in place for '?'
char string[100];
scanf("%s", string);
printf("original_number = %s\n", string);
int i;
int l = strlen(string) - 1;
for (i = 0; i <= l; i++){
new_string[i] = string[l - i];
printf("%c\n", new_string[i]);
}
// add one more char
new_string[i] = '?';
// set the string end
new_string[i + 1] = '\0';
printf("rev_number = %s\n", new_string);
}
Pay attention, that if you fill all the array with 0 as char new_string[101] = {0};, you do not need to add end of string with new_string[i + 1] = '\0';, so the second variant can be shorter if initialization is as in the first one
For both snippets I have the same output
UPDATE:
One more advice on working with strings. When input is made with scanf and you know how much characters can be stored in your array of chars use the following approach to prevent violation of the array boundaries
char string[10]; // if you have 10 bytes
scanf("%9s", string); // ask not more than 9 characters
remember that you need one more byte for '\0' (null terminator).
the problem is you are taking "end of string" as the last input in for loop.you do not need the variable "l". you can do some think like that
int main()
{
char new_string[100];
char string1[100];
scanf("%s",string1);
printf("original_number = %s\n",string1);
int i;
for(i = 0; i<=strlen(string1); i++){
new_string[i] = string1[i-1];
printf("%c\n",new_string[i]);
}
printf("rev_number = %s\n",new_string);
}
#include<stdio.h>
#include<conio.h>
#include<string.h>
char *createP(int);
int main()
{
int n,i;
char str[100];
printf("int n = ");
scanf("%d",&n);
printf("string str = ");
scanf("%s",&str);
if(n>40)
return -1;
for(i=0;i<strlen(str);i++)
if(str[i]=='X' || str[i]=='Y' || str[i]=='Z')
continue;
else
return -1;
char *P;
P=createP(n);
printf("The generated string is = %s",P);
return 0;
}
char *createP(int n)
{
if(n==0)
return "X";
if(n==1)
return "Y";
if(n==2)
return "Z";
if(n>2)
return strcat(createP(n-2),createP(n-3));
}
I am trying to create a string for the following question :
P(0) = 'X'
P(1) = 'Y'
P(2) = 'Z'
P(n) = P(n-2) + P(n-3), n>2
where + denotes string concatenation.
I am using recursion (which looks quite obvious) for this problem.But my .exe is not working.
You are using strcat wrongly.
char * strcat ( char * destination, const char * source );
Appends a copy of the source string to the destination string. The terminating null character >in destination is overwritten by the first character of source, and a null-character is >included at the end of the new string formed by the concatenation of both in destination.
Try using something like this instead,
char *createP(int n)
{
if(n==0)
return "X";
if(n==1)
return "Y";
if(n==2)
return "Z";
if(n>2)
{
char *P = calloc (n, sizeof(char));
strcat(P, createP(n-2));
strcat(P, createP(n-3));
return P;
}
}
You need to create a dynamic list, using only char *P don't let you use it as string at all.
Try to declare char P[100] , and at the end of the recursion put \0 char.
EDIT:
something like that:
void createP(int n,int index)
{
if(n==0)
P[index] = "X";
return ;
if(n>2)
return strcat(createP(n-2,index + 2),createP(n-3,index + 3));
}
While P is global string, and index start with 0.
Memory was not allocated correctly, I had the same problem when I declared
type array[20];
and than called array[20]=...;
The solution was that it was needed to declare type array[21];)
So after a few years of inactivity after studying at uni, I'm trying to build up my c experience with a simple string reverser.
here is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/*
*
*/
int main(int argc, char** argv) {
reverser();
return(0);
}
int reverser(){
printf("Please enter a String: ");
//return (0);
int len;
char input[10];
scanf("%s",&input);
int quit = strcmp(input,"quit");
if(quit == 0){
printf("%s\n","Program quitting");
return(0);
}
len = strlen(input);
printf("%i\n",len);
char reversed[len];
int count = 0;
while (count <= (len-1)){
//printf("%i\n",(len-count));
reversed[count] = input[(len-1)-count];
count++;
}
//printf("%s\n",input);
printf(reversed);
printf("\n");
reverser();
}
When I input "hello", you would expect "olleh" as the response, but I get "olleh:$a ca&#",
How do I just get the string input reversed and returned?
Bombalur
Add a '\0' at the end of the array. (as in, copy only chars until you reach '\0' - which is the point at array[strlen(array)], then when you're done, add a '\0' at the next character)
Strings are conventionally terminated by a zero byte. So it should be
char reversed[len+1];
And you should clear the last byte
reversed[len] = (char)0;
you forgot the \0 at the end of the string
This is because you are creating an array with size 10. When you take in some data into it (using scanf) and the array is not filled up completely, the printf from this array will give junk values in the memory. You should iterate for the length of the input by checking \n.
must have a size + 1 to string length so that you can have a \0 at the end of string that will solve your problem
The following is a (simple and minimal implementation of) string reverse program (obviously, error conditions, corner cases, blank spaces, wider character sets, etc has not been considered).
#include <stdio.h>
int strlen(char *s)
{
char *p = s;
while (*p)
p++;
return p - s;
}
char * strrev(char a[])
{
int i, j;
char temp;
for (i=0, j=strlen(a)-1 ; i<j ; i++, j--) {
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
return a;
}
int main()
{
char str[100];
printf("Enter string: ");
scanf("%s", str);
printf("The reverse is %s \n", strrev(str));
return 0;
}
Hope this helps!