How to remove a specific character from a string in c ?
Eg: if the string is "abcd"
i need to remove the character of index 1
then the result should be , "acd"
My attempt:
void removeSymbol(char *line){
int i,j; char c;
for(i=0;i<strlen(line);i++){
c = *(line +i);
if(!(isdigit(c)||isalpha(c))){ strcpy((line+i),(line+i+1)); }
}
printf("%s\n",line);
}
static inline void removeSymbol(char *line, size_t index){
memmove(&line[index], &line[index+1], strlen(&line[index]));
//printf("%s\n",line);
}
I have changed the prototype of removeSymbol API. I hope this below code will meet your requirements
void removeSymbol(char *line, int index)
{
//Added as per comments
if ( (index > 0 ) && ( index <= strlen (line) ) )
{
//index-> index which needs to be removed.
// +1 is added in memmove last argument to move '\0' character also
memmove (&line[index-1], line + index, strlen (line)-index +1 );
}
}
int main(void){
char symbol [] = "abcdefgh";
removeSymbol (symbol, 8);
printf ("%s\n", symbol);
}
#include <stdio.h>
#include <string.h>
void removSymbol(char *,int);
main()
{
int index=1;
removSymbol("abcd",index);
}
void removSymbol(char *line,int index)
{
int i;
for(i=0;i<strlen(line)-1;i++)
{
if(i<index)
{
*(line+i) = *(line +i);
}
else
{
*(line+i) = *(line+i+1);
}
}
*(line+i+1)='\0';
printf("%s\n",line);
}
Related
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;
}
I am currently practicing using pointers for an upcoming exam and am running through a few practice questions to brush up on them. I want to make my own version of the strrchr function with the given function signature:
char* mystrrchr(char*s, int c) {
And the main field:
int main(void) {
char* s = "ENCE260";
char* foundAt = mystrrchr(s, 'E');
if (foundAt == NULL) {
puts("Not found");
}
else {
printf("%zd\n", foundAt - s);
}
}
And I want the code to work without any changes to the main and function signature.
I want to return the index of the last time the character c appears in a string s as an integer. The jist of the code is fine, I just am unsure how to use the pointers correctly in this situation to return the desired output. For reference the error I am receiving is that I am making a pointer from integer without a cast.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>
#include <assert.h>
char* mystrrchr(char*s, int c) {
int position;
int len = strlen(s);
int i = 0;
while (i < len) {
if (c == s[i]) {
position = i;
i++;
}
else {
i++;
}
}
return position;
}
int main(void) {
char* s = "ENCE260";
char* foundAt = mystrrchr(s, 'E');
if (foundAt == NULL) {
puts("Not found");
}
else {
printf("%zd\n", foundAt - s);
}
}
That is my code thus far.
First you could change
char*mystrrchr(char*s, int c) {
...
return position;
}
to
char*mystrrchr(char*s, int c) {
...
return s + position;
}
because the first version returns the relative position.
Then you also need to initialize position:
char*mystrrchr(char*s, int c) {
int position = -1;
...
}
And then return NULL if nothing was found:
char*mystrrchr(char*s, int c) {
int position = -1;
...
if(position == -1) return NULL;
else return s + position;
}
At this point the function works correctly.
But you could improve the performance by using
while (s[i] != '\0')
instead of using strlen, as Jonathan Leffler pointed out in a comment.
Define mystrrchr as int mystrrchr and call int foundAt = mystrrchr(. Then printf("%d\n", foundAt).
char* mystrrchr(char*s, int c) {
if ( s == NULL ) return NULL;
char *position = NULL;
int i = 0;
while (s[i] != '\0' ) {
if (c == s[i]) {
position = &s[i];
}
i++;
}
return position;
}
You can also go backwards:
char* mystrrchr2(char*s, int c) {
if ( s == NULL ) return NULL;
char *position = NULL;
int i = strlen(s) - 1;
while (i > -1) {
if (c == s[i]) {
position = &s[i];
break;
}
i--;
}
return position;
}
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;
}
Everything seems to work fine while dynamically creating the array
but core dumped while trying to print it backwards.
It managed to print only the last string and then segmentation fault.
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
void init_array(void ***pt, int *ptlen) {
*pt=NULL;
*ptlen=0;
}
void trim_array(void ***pt, int *ptlen, int len) {
*pt=(void**)realloc(*pt, len*sizeof(void*));
*ptlen=len;
}
void write_array(void ***pt, int *ptlen, int pos, void *v) {
if (pos >= *ptlen)
trim_array(pt, ptlen, pos+1);
*pt[pos]=v;
}
void *read_array(void ***pt, int *ptlen, int pos) {
return(*pt[pos]);
}
void destroy_array(void ***pt, int *ptlen) {
trim_array(pt, ptlen, 0);
*pt=NULL;
}
int main(int argc, char *argv[]) {
void **t;
int tlen;
void ***pt = &t;
int *ptlen = &tlen;
char s[256],*p; int i;
init_array(pt, ptlen);
i = 0;
do {
printf("give name:\n");
scanf("%255s",s);
write_array(pt, ptlen, i, (void*)strdup(s));
i++;
} while (strcmp(s,"end"));
for (--i; i>=0; i--) {
p = (char*)read_array(pt, ptlen, i);
printf("%s\n",p);
free(p);
}
destroy_array(pt, ptlen);
return(0);
}
The [] operator has a higher precedence than the * operator. You need to change:
*pt[pos]
to:
(*pt)[pos]
in both places where it occurs.
This error is a direct result of writing almost deliberately confusing code with runaway indirection. You'd save yourself a lot of trouble and make things much easier if you wrapped a lot of this stuff in a struct and created some proper interface functions for it.
Something like this would be a bit better form (although "array" is not really a great name for this data structure):
main.c:
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "array.h"
#define MAX_BUFFER_LEN 255
int main(void) {
Array myarray = array_init(10, true);
/* Loop for input until user enters "end" */
char buffer[MAX_BUFFER_LEN];
while ( true ) {
printf("Give name: ");
fflush(stdout);
/* Get input and remove trailing '\n' if necessary */
fgets(buffer, MAX_BUFFER_LEN, stdin);
size_t last = strlen(buffer) - 1;
if ( buffer[last] == '\n' ) {
buffer[last] = '\0';
}
/* Terminate loop on "end" without adding to array... */
if ( !strcmp(buffer, "end") ) {
break;
}
/* ...or append input to array and continue loop */
array_append(myarray, strdup(buffer));
};
/* Output contents of array */
size_t n = array_size(myarray);
for ( size_t i = 0; i < n; ++i ) {
char * data = array_getdata(myarray, i);
printf("%zu: %s\n", i + 1, data);
}
/* Clean up and exit */
array_destroy(myarray);
return EXIT_SUCCESS;
}
array.h:
#ifndef ARRAY_TYPE_H
#define ARRAY_TYPE_H
#include <stdbool.h>
typedef struct array_type * Array; /* Opaque type for user */
Array array_init(const size_t capacity, const bool free_on_delete);
void array_append(Array array, void * data);
size_t array_size(const Array array);
void * array_getdata(Array array, const size_t index);
void array_deletetop(Array array);
void array_destroy(Array array);
#endif /* ARRAY_TYPE_H */
array.c:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include "array.h"
/* Struct definition is visible only to implementation */
struct array_type {
void ** elements;
size_t capacity;
size_t top;
bool free_on_delete;
};
/* Static functions used by the implementation */
static bool array_isfull(Array array) {
return (array->top + 1) == array->capacity;
}
static void array_resize(Array array, const size_t new_capacity) {
array->capacity = new_capacity;
array->elements = realloc(array->elements,
array->capacity * sizeof (*array->elements));
if ( array->elements == NULL ) {
fputs("Error allocating memory.", stderr);
exit(EXIT_FAILURE);
}
}
/* Interface functions */
Array array_init(const size_t capacity, const bool free_on_delete) {
struct array_type * new_array = malloc(sizeof *new_array);
if ( new_array == NULL ) {
fputs("Error allocating memory.", stderr);
exit(EXIT_FAILURE);
}
new_array->elements = malloc(capacity * sizeof (*new_array->elements));
if ( new_array->elements == NULL ) {
fputs("Error allocating memory.", stderr);
exit(EXIT_FAILURE);
}
new_array->capacity = capacity;
new_array->top = 0;
new_array->free_on_delete = free_on_delete;
return new_array;
}
void array_append(Array array, void * data) {
if ( array_isfull(array) ) {
array_resize(array, array->capacity * 2);
}
array->elements[array->top++] = data;
}
size_t array_size(const Array array) {
return array->top;
}
void * array_getdata(Array array, const size_t index) {
return array->elements[index];
}
void array_deletetop(Array array) {
if ( array->free_on_delete ) {
free(array->elements[array->top - 1]);
}
array->elements[--array->top] = NULL;
}
void array_destroy(Array array) {
while ( array->top > 0 ) {
array_deletetop(array);
}
free(array->elements);
free(array);
}
Sample output:
paul#local:~/src/c/scratch/array$ ./array
Give name: Dave Dee
Give name: Dozy
Give name: Beaky
Give name: Mick
Give name: Titch
Give name: end
1: Dave Dee
2: Dozy
3: Beaky
4: Mick
5: Titch
paul#local:~/src/c/scratch/array$
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);
}