Right Justified Zero filled String in C - c

I want to right justify a string value with zero filled on left hand side. I have written following code but it prints white space instead of 0.
#include<stdio.h>
int main()
{
char s[4]="PJ";
printf("%04s",s);
}
Output: " PJ"
I need output as "00PJ".

You can do something like this :
#define MIN_LEN 4
if (strlen(s) < MIN_LEN) {
printf("%0*d%s", MIN_LEN-(int)strlen(s), 0, s);
}
else {
printf("%s", s);
}
Don't forget to include <string.h>
Edit :
To explain our discussion about buffer overflow, just try this piece of code :
int main()
{
struct
{
char s[4];
int i;
} test;
test.i = 0x12345678;
strcpy(test.s,"PJHA");
printf("Output =%s\nTest =%x",test.s,test.i);
}
Output :
Output =PJHA
Test =12345600
If you change the size to 5, the code is corrected and the stack following your string is not corrupted.

Here is the short line code answer for my question:-
This will take care of any length of input variable like s = "J", s="JH", s="JHA", s="PJHA"
and corresponding output will be "000J", "00JH", "0JHA", "PJHA" .
#include<stdio.h>
#include<string.h>
int main()
{
char s[4],s2[4];
strcpy(s,"JH");
sprintf(s2,"%04s",s);
memset(s2,'0',4-(int)strlen(s));
printf("Output =%s\n",s2);
}
Output =00JH

Appreciate the above simpler solution while giving an alternative more manual one:
#include<stdio.h>
#include<string.h>
void print(char *s, int ncount)
{
if(s == NULL) return;
int len = strlen(s);
if(len > ncount) printf("%s", s);
else {
for(int i = 0; i < ncount - len; ++i)
printf("0");
printf("%s", s);
}
}
int main()
{
char s[4]="PJ";
print(s, 4);
return 0;
}

#include <stdio.h>
#include <string.h>
int main(){
char s[5]="PJ";
char padding[sizeof(s)] = {0};
int width = sizeof(padding)-1;
memset(padding, '0', width);
width -= strlen(s);
//printf("%.*s%s\n", (int)(4-strlen(s)), "0000", s);
printf("%.*s%s\n", width, padding, s);
return 0;
}

Related

need help to fix a pointer array c

#include <stdio.h>
#include <string.h>
void printArray(char* p, int len)
{
for (p; p < p + len; p++)
{
printf("%c", *p);
}
printf("\n");
}
int main(void)
{
char* msg = "hi jyegq meet me at 2 :)";
printArray(msg, strlen(msg));
getchar();
return 0;
}
I've tried to switch some things but I can't understand the problem
I need to fix this code and I think it's with the print of the pointer and I don't know how to print him with no problems
You could do this
#include <stdio.h>
#include <string.h>
void printArray(char* p, int len)
{
;
for (int i = 0; i < len; i++)
{
printf("%c", *(p++));
}
printf("\n");
}
int main(void)
{
char* msg = "hi jyegq meet me at 2 :)";
printArray(msg, strlen(msg));
getchar();
return 0;
}
Use a counter so you wouldn't go somewhere you shouldn't in memory.
Your loop will go on indefinitely. Consider what will happen if you substitute the variables with their values. p > p+len will go from 0 > 0+20 to 1 > 1+20 and so on. This will always be true. A fix could be to first store the endpoint, like for (char *end = p+len; p<end; ++p)
try this code:
#include <stdio.h>
#include <string.h>
void printArray(char* tab, int len)
{
char *p;
for (p=tab; p < tab + len; p++)
{
printf("%c", *p);
}
printf("\n");
}
int main(void)
{
char* msg = "hi jyegq meet me at 2 :)";
printArray(msg, strlen(msg));
getchar();
return 0;
}

search of string in an array of strings

i wrote some code that is supposed to find the location of a given string in an array of strings.
problem is- it doesn't give the location. it gives something else.
i understand that probably the problem has to do with the differences between the pointers that are involved- a previous version that dealt with finding the position of a letter in a word worked well.
after a lot of attempts to figure out where is the bug, i ask your help.
kindly, explain me what should be done.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int what (char * token);
main()
{
int i=0;
char string[]="jsr";
char *token;
token=&string[0];
i=what(token);
printf(" location of input is %d \n", i);
return 0;
}
int what (char * token)
{
int i=1;
char *typtbl[]={"mov",
"cmp",
"add",
"sub",
"not",
"clr",
"lea",
};
char * ptr;
ptr=(char *)typtbl;
while (!(strcmp(ptr,token)==0))
{
ptr=(char *)(typtbl+i);
i++;
}
return i;
}
As pointed out, you did not design function what properly. What value should it return if your search function go through all the pointers but does not find the desired string? Typically in that case return -1 would be a choice to indicate nothing found. Also in this case, using a for loop would probably be more suitable, you can just return the index immediately instead of going through all pointers.
int what(char *token)
{
char *typtbl[] = {
"mov",
"cmp",
"add",
"sub",
"not",
"clr",
"lea",
};
for( size_t i = 0; i < sizeof(typtbl)/sizeof(char*); ++i )
{
char *ptr = typtbl[i];
if(strcmp(ptr, token) == 0)
{
return i; // found something
}
}
return -1; // found nothing
}
A cleaner working version.
Main issue is in the (char *)(typtbl+i) replaced by typtbl[i] in the following code. typtbl+i is equivalent to &typtbl[i], so if my memory is good, it's a pointer on the pointer of the string and not the pointer of string itself
I added a NULL at the end of the array to be able to stop if the string is not present and return -1 to clearly say it was not found.
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int what(char *token);
int main()
{
int i = 0;
char string[] = "jsr";
i = what(string);
printf(" location of input is %d \n", i);
return 0;
}
int what(char *token)
{
char *typtbl[] = {
"mov",
"cmp",
"add",
"jsr",
"not",
"clr",
"lea",
NULL
};
int i = 0;
while(typtbl[i] && !(strcmp(typtbl[i], token) == 0)) {
++i;
}
if(!typtbl[i])
i = -1;
return i;
}
char *token; token=&string[0]; was useless because string == &string[0].
A few things:
Your main function is missing its return type.
The while loop in what doesn't stop when the element isn't found. Therefore you are reading out of bounds.
This should do the work w/o pointer arithmetic.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int what (char * token);
int main(){
int i=0;
char string[]="jsr";
char *token;
token=&string[0];
i=what(token);
printf(" location of input is %d \n", i);
return 0;
}
int what (char * token){
unsigned int i=0;
char *typtbl[]={"mov",
"cmp",
"add",
"sub",
"not",
"clr",
"lea",
};
unsigned int typtbl_x_size = sizeof(typtbl)/sizeof(typtbl[0]);
char * ptr;
ptr=typtbl[i];
while (!(strcmp(ptr,token)==0)){
i += 1;
if (i >= typtbl_x_size){
printf("element not in list\n");
return -1;
}
ptr=typtbl[i];
}
return i;
}

Cut out section of a string with another string

I got this part of a C program:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void){
char *mRNA = spleissen("AUAGUAAAAGCUCUGUUUAGGAGA", "GU", "AG");
printf("mRNA: %s\n", mRNA);
free(mRNA);
return 0;
}
I have to write the function spleissen which should work like this: it cuts out a string which goes from a GU to an AG and everything in between those two. So the program output is:
mRNA: AUACUCUGAGA
I don't really know how I can cut those parts out.
I am not allowed to use includes other than stdio, string and stdlib.
char *spleissen(const char *src, const char *start, const char *end){
size_t len = strlen(src);
char *s, *e, *ret, *work;
ret = work = malloc(len + 1);
strcpy(work, src);
len = strlen(end);
while(s = strstr(work, start)){
if((e = strstr(s, end))==NULL)
break;//delete upto last?
memmove(s, e + len, strlen(e+len)+1);
work = s;
}
return ret;
}
I think you can simply do this:
char *spleissen(char *array, char *G, char *A)
{
int l=strlen(array);
int i, j=0;
char returnstr[10010];
int b=0;
for(i=0; i<l; i++)
{
if(G[0]==array[i] && G[1]==array[i+1])
{
b=1, i++;
continue;
}
else if(A[0]==array[i] && A[1]==array[i+1] && b==1)
{
b=0, i++;
continue;
}
if(b==0)
{
returnstr[j]=array[i];
j++;
}
}
return returnstr;
}

Wrong output in my stringreverse program. what is fault in my code?

#include<stdio.h>
#include<conio.h>
#include<string.h>
char* strreverse(char*);
int main()
{
char *rev_string;
char *name="computer";
clrscr();
rev_string=strreverse(name);
printf("%s", rev_string);
getch();
return 0;
}
char* strreverse(char *name)
{
int length=strlen(name);
char *ptr;
char *rstr;
for(ptr=name+(length-1);ptr>=name;ptr--)
{
*rstr=*ptr;
printf("%c",rstr);
rstr++;
}
*(rstr)=NULL;
return rstr;
}
the above is my code. i tried to write a program for string reverse without using arrays. But i am not getting the output retupmoc. what is wrong in my code? how to insert null char in char*?
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <stdlib.h>
char* strreverse(const char*);
int main(){
char *rev_string;
char *name="computer";
clrscr();
rev_string=strreverse(name);
printf("%s\n", rev_string);
free(rev_string);
getch();
return 0;
}
char* strreverse(const char *name){
int length=strlen(name);
const char *ptr;
char *ret, *rstr = malloc(length + 1);
if(ret=rstr){
for(ptr=name+length;ptr != name;){
*rstr++ = *--ptr;
}
*rstr = '\0';
}
return ret;
}
You did not allocate memory to hold your reversed string. Try
char *rstr = calloc(1, length+1);
Also it should be
printf("%c", *rstr); // dereference
*(rstr)= '\0'; // instead of NULL
Here you find sweet and short solution for string reverse:
#include<stdio.h>
#include<string.h>
int strreverse(char* , char*);
int main()
{
char rev_string[10] = {0};
char name[10]="computer";
strreverse(name, rev_string);
printf("%s\n", rev_string);
return 0;
}
int strreverse(char *name, char *rStr)
{
int i = 0;
int length = strlen(name);
while(i < length)
{
rStr[i] = name[length-i-1];
i++;
}
return 0;
}
Try to run and have fun.

Reversing a string in c with recursion

I have written code to reverse a string in c... it works fine but I can't return the reversed string in the main() function.
#include<stdio.h>
main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
int reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}
it prints the reversed string but I want the reversed string in main(). How can I do this?
Following is one way to reverse string using recursion!
#include <stdio.h>
#include <string.h>
void rev_str_recursive(char arr[], size_t iStart, size_t iLast)
{
if( iStart < iLast )
{
//swap
char temp = arr[iStart];
arr[iStart] = arr[iLast];
arr[iLast] = temp;
rev_str_recursive(arr, ++iStart, --iLast);
}
}
void main()
{
char cArray[] = {"A quick brown fox jumps over a lazy dog"};
rev_str_recursive(cArray, 0, strlen(cArray)-1);
}
You need to modify the string, i.e. the input buffer to reverse(), instead of just printing it.
Doing this recursively seems a bit obnoxious, but should of course be possible.
Basically, I guess the printing becomes an assignment, something like this:
Base: The reversal of an empty string is the empty string.
Step: The reversal of a string begins by swapping the first and last characters, then recursing over the remainder of the string.
Here is another way to reverse a string using recursion:
void reverseString(char* dest, char *src, int len) {
if (src == NULL || len == 0)
return;
reverseString(dest, src + 1, len - 1);
strncat_s(dest, len + 1, src, 1);
}
You can call like that:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define STRING "Let's try this one."
#define SIZE 20
void main() {
char* src = (char*)malloc(SIZE);
char* dest = (char*)malloc(SIZE);
strcpy_s(dest, SIZE, "");
strcpy_s(src, SIZE, STRING);
reverseString(dest, src, strlen(src));
/* Do anything with dest. */
// printf("%s\n", dest);
free(src);
free(dest);
}
This code is not executable :(
You define int reverse but reverse function doesnt return any value
instead use this (using void):
#include<stdio.h>
main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
void reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}
#include <iostream>
using namespace std;
reverse( char *str)
{
if (*str!='\0')
{
reverse(str+1);
cout<<*str;
}
//cout<<*str when i am just printing here then why this is printing after one space ??
}
int main()
{
string a ;
cin>>a;
reverse(&a[0]);
return 0;
}
a little change in Emre Can Kucukoglu's answer . . .
we can eliminate strncat_s
void revstr_rec(char *sstr, char *dstr, int len)
{
int i = 0;
if((! *sstr) || (! len) )
return;
revstr_rec(sstr + 1, dstr, len - 1);
dstr[len - 1] = *sstr;
return;
}
int main()
{
char *sstr = NULL;
char *dstr = NULL;
sstr = malloc(16);
if(! sstr) {
printf("no memory . . .\n");
return 0;
}
strcpy(sstr, "hello world !");
printf("sstr: %s\n", sstr);
dstr = malloc(16);
if(! dstr) {
printf("no memory . . .\n");
return 0;
}
revstr_rec(sstr, dstr, strlen(sstr));
printf("dstr(recursive): %s\n", dstr);
free(sstr);
free(dstr);
return 0;
}
#include <stdio.h>
#define MAX 100
int main()
{
char str[MAX], *rev;
scanf("%s", str);
rev = reverse(str);
printf("The reversed string is : %s\n", rev);
return 0;
}
char *reverse(char ch[])
{
static char r[MAX];
static int i=0;
if(*ch == '\0') return "";
else
{
reverse(ch+1);
r[i++]=*ch;
}
return r;
}
A simple way with left and right index
void main()
{
char* str = (char*)malloc(strlen("somestring")+1);
strcpy(str, "somestring");
int leftIndex = 0;
int rightIndex = strlen(str) - 1;
printf("%s\n", ReverseString(str, leftIndex, rightIndex));
free(str);
}
char* ReverseString(char* str, int leftIndex, int rightIndex)
{
if (leftIndex == rightIndex || leftIndex == (rightIndex +1)) {
return str;
}
// flip letters
char leftLetter = *(str + leftIndex);
char rightLetter = *(str + rightIndex);
*(str + leftIndex) = rightLetter;
*(str + rightIndex) = leftLetter;
return ReverseString(str, leftIndex+1, rightIndex -1);
}
use sprintf it will print your reversed string into buffer.
#include<stdio.h>
char *b;
main()
{
char a[17]="abcdefg";
char buffer[17];
buffer[0]= '\0';
b = buffer;
reverse(a);
printf("%s\n",buffer);
}
int reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
sprintf(b,"%c",*a);
b++;
}
}
void palindromo(char *s)
{
if(s[0] != '\0'){
palindromo(s+1);
printf("%c", s[0]);
}
}
This is a small recursive function who print the string inverted.
#include<stdio.h>
#include<string.h>
void rev(char *);
int main()
{
char s[]="Hello";
printf("\n%s",s);
rev(s);
printf("\n%s",s);
return 0;
}
void rev(char *s)
{
static int i=0;
static int j=0;
if(j==0) //since static variable can be intitialized
{ //only with a constant literal,to store
j=strlen(s)-1; //length-1 in 1st function call, we can use
} //this trick.(condition satisfied only in 1st
//function call)
if(i<j)
{
char temp;
temp=s[i];
s[i]=s[j]; //Analogous to for(i=0,j=l-1;i<j;i++,j--)
s[j]=temp; // { //swap code }
i++;
j--;
rev(s);
}
}
#include<stdio.h>
void reverse(char *a);
main()
{
char a[17]="abcdefg";
reverse(a);
printf("\n");
system("PAUSE");
}
void reverse(char *a)
{
if(*a!='\0')
{
reverse(a+1);
}
printf("%c",*a);
}

Resources