Reversing a string using two pointers in C - c

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]

Related

Making a string of usergiven_character*usergiven_repeatsinthestring(number of repeats)

I think that the problem is with allocating the memory for the string, but probably there is more to it
What i have to do is get a character and a number from the user
And print a string that has the character appear in it number times
Like i give character: $ and number: 8
I need to make a string :$$$$$$$$
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int *ptr;
char *string;
//Space for number
ptr = (int *) calloc(1,sizeof(int));
//Get number
printf("Give any number: \n");
scanf("%i",ptr);
fflush(stdin);
//Space for string(+1 for \0)
string = (char *) calloc(*ptr+1,sizeof(char));
//Get string
printf("Give any character: \n");
gets(string);
//They dont give the *ptr+1 memory that i give to string
printf("Size of string is: %i\n",sizeof(string));
printf("Size of string is: %i\n",strlen(string));
//I put the character *ptr times in the string
for ( char *x = string; x-string<*ptr; x++)
strcpy(x,string);
//I print it
printf("String is: ");
puts(string);
free(string);
free(ptr);
return 0;
}
This works-----------------------------------------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int *ptr;
char *string,*x,*c;
//Space for number
ptr = (int *) calloc(1,sizeof(int));
//Get number
printf("Give any number: \n");
scanf("%i",ptr);
//Space for string(+1 for \0)
string = (char *) calloc(*ptr+1,sizeof(char));
//Get string
printf("Give any character: \n");
scanf(" %c",string);
//This was the problem
c = (char *) calloc(1,sizeof(char));
*c = *string;
//I put the character *ptr times in the string
for ( x = string; x-string<*ptr; x++)
strcpy(x,c);
//Just checking
printf("Size of string is: %i\n\n",strlen(string));
//I print it
printf("String is: %s\n\n",string);
free(string);
free(ptr);
return 0;
}
Suggest at a minimum the following changes/suggestions: (read comments as well.)
//Space for number
// ptr = (int *) calloc(1,sizeof(int));
// ^^^^^^^
ptr = calloc(1,sizeof(int)); //No need to cast return of calloc in C.
// However,
int val = 0;
// would be a better choice of creating space for an integer.
// (unless this is an assignment.)
//Get number
printf("Give any number: \n");
scanf("%i",ptr);
// or, if using val
scanf("%i", &val); //needs the address of operator for non pointer variable
//fflush(stdin); // undefined behavior to do this
//Space for string(+1 for \0)
//string = (char *) calloc(*ptr+1,sizeof(char));
char string[12] = {0}; //simplify, define a char array and use it instead
//note the largest likely length of an integer is
//represented in a string is 11: "-2147483648"
// plus the nul character, thus string size is 12.
char c = 0;
//Get string - not really getting a string from user, but a char.
//get char (more accurate description on what you are actually doing
printf("Give any character: \n");
//gets(string);
// place user input into a string
scanf(" %c"m &c); //note the space in front of %c. It consumes newline character.
If you have a character and a number, say variables c and ptr, then the sprintf statement becomes:
sprintf(string, "%c%d", c, ptr);
Given c == $ and ptr == 5, the loop to produce $$$$$ could be:
memset(string, 0, strlen(string)+1);
for(int i = 0; i<ptr; i++)
{
string[i] = c;
}
strcat(string[i] = 0; // terminate with nul character
string is now ready to print by any of these methods:
printf(string); or
printf("%s", string); or
fputs(string, stdout); or
puts(string);

reverse string in c incorrect output

I was writing a program to reverse an entered string in C and my code is :
#include<stdio.h>
#include<string.h>
void main()
{
int sz;
printf("Enter the size of the string : ");
scanf("%d",&sz);
char str[sz];
gets(str);
printf("Enter the string : \n");
gets(str);
char str1[sz];
int i =0;
--sz;
for(i=0;i<=sz;i++)
{
str1[sz-i]=str[i];
}
printf("%s",str1);
}
well this program is giving an weird output for string sizes 8,9 and 10
for size 8 the reversed string is being printed followed by a space and 2 garbage characters,for size 9 the reversed string is being printed followed by 2 garbage characters and for size 10 the reversed string is being printed by a garbage character and for other string sizes the program is running properly. why is this happening?
Note:
It is not smart to try to limit the input string by asking the user, the user can still write string with length greater/ less
Reading string from console does by default not allow spaces
First option:
Read a string of a static size:
char original[5];
scanf("%5s", original); // String containing 5 chars
Second option:
Read a string of variable size:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
// Length of String
unsigned expected;
printf("Enter the length of the string: ");
scanf("%u", &expected);
char *temp; // Warning: Uninitialized
// Get string
printf("Enter the string: ");
scanf("%s", temp);
unsigned actual = strlen(temp);
unsigned length = actual > expected ? expected : actual;
char *string = (char *) malloc(length * sizeof(char));
char *reverse = (char *) malloc(length * sizeof(char));
// Trim string to proper size
for (int i = 0; i < length; i++) {
string[i] = temp[i];
}
// Reverse string
for (int i = 0, j = length - 1; i <= j; i++) {
reverse[i] = string[j - i];
}
// Print Strings
printf("%s", string);
printf("\n%s", reverse);

Beginner C, why is a bunch of random stuff added to my string?

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.

Concatenation of two strings with discarding overlap

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

Problems with simple c task

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!

Resources