Junk values while reversing a string? - c

My program is to reverse, even though the reverse is being generated but the problem is there is an unwanted junk values too.
I am not able to understand where the problem is.
#include <stdio.h>
#include<string.h>
int main()
{
char ar[100],b[100];
int i,j;
scanf("%s",ar);
j=strlen(ar);
printf("%d",j);
j-=1;
for(i=0;j>=0;i++)
{
b[i]=ar[j];
j--;
}
printf("\n %s",b);
}
This is the output:

You need to add
b[i] = 0;
at the end to terminate the string.

The function printf() depends on the NUL-terminating character as a marker to stop printing, so you should terminate your array with the character '\0'. Also it would be better to make a function to reverse a string:
#include <stdio.h>
#include <string.h>
void m_strrev(char *str, char *output);
int main(void)
{
char ar[100], b[100];
//int i, j;
scanf("%s", ar);
/*j = strlen(ar) - 1;
for (i = 0; j >= 0; i++)
{
b[i] = ar[j];
j--;
}
b[i] = '\0';
printf("%s\n", b);*/
m_strrev(ar, b);
printf("%s\n", b);
}
void m_strrev(char *str, char *output)
{
char *e = str;
while (*e) {
e++;
}
e--;
while (e >= str) {
*output++ = *e--;
}
*output = '\0';
}

Related

separate numbers and string into text and numbers

I am trying to write code where I can separate string and numbers.
The string I have to separate it completely already the numbers I have to separate every 2 numbers.
My Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void getString(const char *str) {
char nums[50];
char alphas[50];
for (int i = 0; i < strlen(str); i++) {
if (isdigit(str[i]))
strcpy(nums, str);
if (isalpha(str[i]))
strcpy(alphas, str);
}
printf("str: %s\n", alphas);
printf("num: %d\n", atoi(nums));
}
int main() {
char *str = "one01two02three03";
getString(str);
return 0;
}
What I'm trying to do should return me as follows
str: onetwothree
num1: 01
num2: 02
num3: 03
The following parses the input and produces the correct output.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
int *nums = NULL;
int num_count = 0;
char save_num(int n)
{
nums = realloc(nums, sizeof(int)*(num_count+1));
nums[num_count++] = n;
return '\0';
}
void getString(const char *str)
{
char* alpha = malloc(strlen(str)+1);
char* num = malloc(strlen(str)+1);
size_t i;
alpha[0] = '\0';
num[0] = '\0';
for (i = 0; i < strlen(str); i++)
{
if (isdigit(str[i]))
strncat(num, str+i, 1);
else if(isalpha(str[i]))
{
strncat(alpha, str+i, 1);
if(strlen(num) > 0)
num[0] = save_num(atoi(num));
}
}
if(strlen(num) > 0)
save_num(atoi(num));
printf("str: %s\n", alpha);
for(i = 0 ; i < num_count ; ++i)
printf("num%Zu: %02d\n", i+1, nums[i]);
free(alpha);
free(num);
}
int main()
{
char *str = "one01two02three03";
getString(str);
return 0;
}
This provides what you have asked for:
void getString(const char *str)
{
char one[10],two[10],three[10];
int x,y,z;
char a[10],b[10],c[10];
sscanf(str,"%[^0-9]""%[0-9]""%[^0-9]""%[0-9]""%[^0-9]""%[0-9]",a,one,b,two,c,three);
x = atoi(one);
y = atoi(two);
z = atoi(three);
printf("str: %s%s%s\n",a,b,c);
printf("num: %d\n",x);
printf("num: %d\n",y);
printf("num: %d\n",z);
}
DonĀ“t forget to provide the declaration of getString before main():
void getString(const char *str);
So all together:
#include <stdio.h>
void getString(const char *str);
int main()
{
char *str = "one01two02three03";
getString(str);
return 0;
}
void getString(const char *str)
{
char one[10],two[10],three[10];
int x,y,z;
char a[10],b[10],c[10];
sscanf(str,"%[^0-9]""%[0-9]""%[^0-9]""%[0-9]""%[^0-9]""%[0-9]",a,one,b,two,c,three);
x = atoi(one);
y = atoi(two);
z = atoi(three);
printf("str: %s%s%s\n",a,b,c);
printf("num: %d\n",x);
printf("num: %d\n",y);
printf("num: %d\n",z);
}
Output:
str: onetwothree
num: 01
num: 02
num: 03
Since you have already set your strings 'nums' and 'alphas' there is no need to handle them dynamically.You should just copy the elements of the array str,one by one, to either the array num or the array alphas.
To distinguish different numbers just put a special character between numbers in the num array.
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
void getString(const char *str)
{
char nums[50];
char alphas[50];
int digits = 0;
int alpha = 0;
for (int i = 0; i < strlen(str); i++) {
if (isdigit(str[i])){
while(isdigit(str[i])){
nums[digits] = str[i];
i++;
digits++;
}
nums[digits]='\n';
digits++;
}
if(isalpha(str[i])){
alphas[alpha] = str[i];
alpha++;
}
}
printf("str: %s\n", alphas);
int n,p=0;
char subbuf[5];
for(n=0;n<digits;n++){
p=n;
while(nums[n]!='\n'){
n++;
}
memcpy(subbuf,&nums[p],n-p);
printf("num: %d\n", atoi(subbuf));
}
}
int main()
{
char *str = "01two02three03";
getString(str);
return 0;
}
Be aware that strcpy sets the pointer of the first argument to point to the second argument,this means that when you write strcpy(nums,str) in your code above, you copy the entire str string to the num several times.
Using an array for this question is not necessary, unless the array is to be used later. So my answer to this question is short and simple:
#include <stdio.h>
#include <stdbool.h>
void getString(const char *str)
{
bool in_number = false;
while (*str) {
if (*str >= '0' && *str <= '9') {
if (!in_number) { // Transition from a non-digit to digit
printf(": ");
in_number = true;
}
} else if (in_number) { // Transition from a digit to non-digit
putchar('\n');
in_number = false;
}
putchar(*str++);
}
putchar('\n');
}
int main(void)
{
char *str = "one01two02three03";
getString(str);
return 0;
}
The boolean variable in_number is used to catch the transitions from a digit character to a non-digit character and from a non-digit character to a digit character.

Reverse string function not working properly

Here is my code. I just can't seem to figure it out. Sometimes i get no output, and sometimes i just get 3 random characters, regardless of how long the entered string is.
#include <stdio.h>
#include <math.h>
#include <string.h>
void reverse(char* array, int numberOfChars);
int main()
{
char string[250];
int length;
printf("Enter a string: ");
gets(string);
printf("How long is the string:");
scanf("%d", &length);
reverse(string, length);
printf("Reversed string is: %s\n"), string;
return 0;
}
void reverse(char *userArray, int numberOfChars)
{
char temp;
int fromEnd = 0, fromStart = 0;
fromEnd = numberOfChars;
while (fromStart < fromEnd)
{
temp = userArray[fromStart];
userArray[fromStart] = userArray[fromEnd];
userArray[fromEnd] = temp;
fromStart++;
fromEnd--;
}
}
I really dread asking these questions here but I can't seem to fix it...
Any help appreciated
Conceptually you need to swap the ends until you are left with a string of length 0 or 1. You don't need to test for the length of the remaining portion of the string after each iteration however, because it can be shown that exactly length/2 swaps will be needed.
void reverse (char *s)
{
size_t length = strlen (s);
for (size_t i = 0; i < length / 2; i++) {
char tmp;
tmp = s[i];
s[i] = s[length - 1 - i];
s[length - 1 - i] = tmp;
}
}
There is no need to complicate things like that, try this:
#include <stdio.h>
int main(void){
char *src = "Michi";
char dest[256];
int i=-1,j=0;
while(src[++i]!='\0');
while(i>=0){
dest[j++] = src[--i];
}
dest[j]='\0';
printf("Your new string is: %s",dest);
return 0;
}
Output:
Your new string is: ihciM
This is probably what you need:
#include<stdio.h>
#include<string.h>
void reverse(char *ptr);
int main(void) {
char src[256] = "Michi";
reverse(src);
printf("Your new string is: %s",src);
return (0);
}
void reverse(char *src){
char dest;
size_t i, j = 0;
i = 0;
j = strlen(src) - 1;
while (i < j) {
dest = src[i];
src[i] = src[j];
src[j] = dest;
i++;
j--;
}
}
don't use gets(),use fgets().To reverse strings,you don't need to pass number of characters,since strings in C are null-terminated.check this very simple function:
#include <stdio.h>
void reverse(char *_Str);
int main(void)
{
char str[] = "Hello Buddy";
reverse(str);
printf("%s\n",str);
return 0;
}
void reverse(char *_Str)
{
char tmp,*_b,*_e;
_b = _e = _Str;
while(*_e) _e++;
_e--;
while(_b < _e)
{
tmp = *_b;
*_b++ = *_e;
*_e-- = tmp;
}
}
Well the very important line you missed is assigning the null character. And do not take the length of your string as an input from the user. use the function some_integer=strlen(stringname); This will return the length of your stringname and assign it to some_integer. Your function to reverse the string should be as
void reverse(char *userarray) // no need of a second argument. Do not trust your users.
{
char temp;
int fromEnd,fromStart = 0; /
fromEnd = strlen(userarray)-1; // here the length of your string is assigned to fromEnd.
while (fromStart < fromEnd)
{
temp = userArray[fromStart];
userArray[fromStart] = userArray[fromEnd];
userArray[fromEnd] = temp;
fromStart++;
fromEnd--;
}
userarray[strlen(userarray)-1]='\0'; //You missed this line (very important)
}
And chek your printf statement.
It should be
printf("Your reversed string is %s \n",string);
not
printf("Your reversed string is %s \n"),string;
I belive this will work. Check it and let me know if it works for you.
Incorrect code. The needed string for the printf() is not in the function. #M Oehm
/// printf("Reversed string is: %s\n"), string;
printf("Reversed string is: %s\n", string);
Also original code can easily wipe out the string terminating null character '\0'. Better to use strlen(string) rather than ask the user for the length.
Likely should use - 1 as commented by #WalterM. It is unclear what values OP is using.
// fromEnd = numberOfChars;
if (numberOfChars <= 0) return;
fromEnd = numberOfChars - 1;
Answers I have seen so far depend on int well addressing all elements of a string. size_t is the right approach as int may be too small.
Many answers would fail on a string such as "".
So here is another contribution without those restrictions.
#include <string.h>
#include <stdio.h>
char *str_revese_inplace(char *s) {
char *left = s;
char *right = s + strlen(s);
while (right > left) {
right--;
char t = *right;
*right = *left;
*left = t;
left++;
}
return s;
}
void stest(const char *s) {
char t[strlen(s) + 1];
// or char t[100];
strcpy(t, s);
printf("'%s' --> '%s'\n", s, str_revese_inplace(t));
}
int main(void) {
stest("123");
stest("12");
stest("1");
stest("");
return 0;
}
Output
'123' --> '321'
'12' --> '21'
'1' --> '1'
'' --> ''

C program for how to reverse a number explanation needed

While searching for a C program on how to reverse a string, i came across the below program. I am already familiar with a program where we take the length of the string and then minus each character and find the reverse. But this a different program. So can someone please tell me how this code works? Help will be gratefully accepted.
compiler used is Borland Turbo c.
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main() {
char str[50];
char rev[50];
int i, j, n;
clrscr();
printf("enter the string to be reversed:");
scanf("%s", &str);
for (i = 0; str[i] != 0; i++) {
n = i - 1;
}
for (j = 0; j <= i - 1; j++) {
rev[j] = str[i];
n--;
}
printf("the reverse of the string is:%s", rev);
getch();
}
In C, strings are NUL-terminated meaning that it has '\0' at the end signifying the end of the string. The code you've posted currently has two issues:
This:
scanf("%s", &str);
should be
scanf("%s", str);
as %s expects a char*, not a char(*)[50].
This:
rev[j] = str[i];
should be
rev[j] = str[n];
rev should be NUL-terminated before printing. Add
rev[j] = '\0';
just before
printf("the reverse of the string is:%s", rev);
to avoid Undefined Behavior.
Your code doesn't work as it is supposed to.Have you tried it ?
Consider this approach to reverse a string :
#include <stdio.h>
#include <string.h>
int reverse(char *Str);
void swap(char *x, char *y);
int main(int argc, char *argv[]) {
char Str[255];
printf("enter the string to be reversed : ");
scanf("%s", Str);
reverse(Str);
printf("the reverse of the string is : %s\n", Str);
}
int reverse(char *Str) {
size_t len = strlen(Str);
size_t n = len / 2;
char *begin = Str;
char *end = (Str + len) - 1;
while (n > 0) {
swap(begin, end);
begin++;
end--;
n--;
}
return 0;
}
void swap(char *x, char *y) {
char tmp;
tmp = *x;
*x = *y;
*y = tmp;
}

Palindrome Checker in C

Where should I include toupper() in my code in order to make a palindrome such as Noon or NoOoON to say it is a palindrome rather than saying it is not a palindrome. I can't seem to figure it out. Thanks.
#include <stdio.h>
#include <string.h>
#include <ctype.h>
void reverse(char s[]){
int c, i , j;
for (i = 0, j = strlen(s)-1; i < j; i++, j--) {
c = s[i];
s[i] = s[j];
s[j] = c;
}
return;
}
int main(){
char a[20];
char b[20];
printf("Enter a string:\n");
gets(a);
strcpy(b,a); // copies string a to b
reverse(a); // reverses string b
if(strcmp(a, b) == 0) { // compares if the original and reverse strings are the same
printf("The string is a Palindrome\n");
}
else {
printf("The string is not a Palindrome\n");
}
return 0;
}
In your case, you can just use _stricmp instead of strcmp.
Another way to approach this is to convert your string to a single case after it is input. eg
for (char *c = a; *c; c++) *c = toupper(*c);
If you want to use toupper() then you should apply it before you make a copy of the string and reverse it.
That is:
int main() {
char a[20];
char b[20];
int i = 0;
printf("Enter a string:\n");
gets(a);
// make the change here
for (i = 0; i < strlen(a); i++) {
a[i] = toupper(a[i]);
}
strcpy(b, a);
If you convert the string to a single case later, then the copy will not be the same as the original, or you'd have to toupper() both.

string reverse program in C

i have written a program to reverse a string.. But it is not working.. It is printing the same string which is scanned.. What is the problem with the code?
#include <stdio.h>
#include <stdlib.h>
char *strrev(char *s)
{
char *temp = s;
char *result = s;
char t;
int l = 0, i;
while (*temp) {
l++;
temp++;
}
temp--;
for (i = 0; i < l; i++) {
t = *temp;
*temp = *s;
*s = t;
s++;
temp--;
}
return result;
}
int main()
{
char *str;
str = malloc(50);
printf("Enter a string: ");
scanf("%s", str);
printf("%s\n\n", strrev(str));
return 0;
}
for (i = 0; i < l; i++)
You're walking through the entire string, so you're reversing it twice - it won't be reversed after all. Walk only halfways:
for (i = 0; i < l / 2; i++)
Also, try using int len = strlen() instead of the while-not-end-of-string loop, if you're permitted to do so.
You swap the string's content twice.
Use the following code ..
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
char *strrev(char *s)
{
char *temp = s;
char *result = s;
char t;
while (*temp)
temp++;
while (--temp != s)
{
t = *temp;
*temp = *s;
*s++ = t;
}
return result;
}
int main()
{
char *str;
str = (char*)malloc(50);
printf("Enter a string: ");
scanf("%s", str);
printf("%s\n\n", strrev(str));
return 0;
}
The logic is to swap characters from start upto first half with the characters from last of second half, i.e, upto len/2. Just modify your for loop as below & it will work fine for you
for (i = 0; i < l/2; i++) {
you can use this simple code
#include "stdafx.h"
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
int str_len (char *str)
{
char *ptr = str;
while (*str)
str++;
return str - ptr;
}
int main ()
{
char *str;
int length;
str = (char*)malloc(50);
printf("Enter a string: ");
scanf("%s", str);
length = str_len(str) - 1;
for (int i = length ; i >= 0 ; i--)
printf ("%c", str[i]);
return 0;
}
you can use this code to reverse the string
#include<stdio.h>
#include<string.h>
int main()
{
int n,i;
char str2[100],str1[100];
printf("enter teh string 1\n");
gets(str1);
n = strlen(str1);
for(i=0;i<n;i++)
{
str2[n-1-i]=str1[i];
}
printf("%s\n",str2);
}
Actually you are reversing the string twice...so after come to middle of the string, you should terminate the loop that is your loop should be run for half of the string length that is l/2 (in this case). so your loop should be like
for(i = 0; i < i / 2; i++)
swapping the string content twice..
swapping it once will help..
for (i = 0; i < l/2; i++)

Resources