How can I access the certain indexes of string using the function? - c

I was practicing and found some exercise on the internet and it says that I should copy str2 to str1, perhaps the main problem is that I should copy only a certain index of that string (so from str2[a] to str2[b]). Therefore A and B should be entered so they reduce the range of copied indexes to str1. So here I used the function method to tackle this problem but something went wrong. So I don't get why function does not work, there must be a big mistake in my understanding or I did it all wrong.
#include <stdio.h>
#include <string.h>
#define N 50
void myfunction(char str1[], char str2[], int a, int b);
int main() {
char str1[N], str2[N];
int a, b;
printf("please input str1:");
gets(str1);
printf("please input str2:");
gets(str2);
printf("please input a and b:");
scanf("%d%d", &a, &b);
printf("str2=%s, str1=%s", str2, str1);
myfunction(str1, str2, a, b);
return 0;
}
void myfunction(char str1[], char str2[], int a, int b) {
int i, j;
for (i = a; i <= b; i++) {
str1 += str2[i];
}
}

I should copy str2 to str1, perhaps the main problem is that I should
copy only a certain index of that string (so from str2[a] to str2[b]).
It looks like you need to copy a part of one string in another character array starting from its initial position and as a result the character array shall also keep a string built from characters of the first string.
If so then the function should be declared like
char * myfunction( char str1[], const char str2[], size_t n );
that is one of parameters of your original function is redundand because using the pointer arithmetic you can always call the function like
myfunction( str1, str2 + a, b - a + 1 );
In your function implementation it seems there are typos.
void myfunction(char str1[], char str2[], int a, int b) {
int i, j;
for (i = a; i <= b; i++) {
str1 += str2[i];
}
}
For example the variable j is not used, And in this assignment statement
str1 += str2[i];
the left operand is a pointer. So you are just increasing the pointer itself without copying anything. For example if str2[i] contains the character 'A' then the above statement looks like
str1 += 'A';
If there is used the ASCII character table then the statement is equivalent to
str1 += 65;
That is the address stored in the pointer str1 is increased by 65 and will point beyond the destination array.
Also in main there is no great sense to input a string in the character array str1 because as it is supposed it will be overwritten in the function.
Pay attention to the function gets is unsafe and is not supported by the C Standard any more. Instead you should use the function fgets.
Here is a demonstrative program that shows how the function can be written without using standard string functions.
#include <stdio.h>
#define N 50
char * myfunction( char str1[], const char str2[], size_t n )
{
char *p = str1;
while ( *str2 && n-- )
{
*p++ = *str2++;
}
*p = '\0';
return str1;
}
int main(void)
{
char str1[N];
char str2[N] = "Hello World!";
puts( str2 );
puts( myfunction( str1, str2 + 6, 6 ) );
return 0;
}
The program output is
Hello World!
World!
If you will change the function the following way
char * myfunction( char str1[], const char str2[], size_t n )
{
char *p = str1;
while ( *str2 && n )
{
*p++ = *str2++;
--n;
}
while ( n-- ) *p++ = '\0';
return str1;
}
then it will behave the same way as the standard string function strncpy declared in the header <string.h> which you should familiarize yourself with.

There are multiple problems in your program:
you should not use gets()
myfunction just increments str1 instead of copying characters.
you should output the resulting string.
Here is modified version:
#include <stdio.h>
#include <string.h>
#define N 50
void myfunction(char str1[], char str2[], int a, int b);
// safe replacement for gets()
char *mygets(char *buf, size_t n) {
int c;
size_t i;
while ((c = getchar()) != '\n') {
if (c == EOF) {
if (i == 0)
return NULL;
break;
}
if (i + 1 < n)
buf[i++] = c;
}
if (i < n) {
buf[i] = '\0';
}
return buf;
}
int main() {
char str1[N], str2[N];
int a, b;
printf("please input str1: ");
if (!mygets(str1, sizeof str1))
return 1;
printf("please input str2: ");
if (!mygets(str2, sizeof str2))
return 1;
printf("please input a and b: ");
if (scanf("%d%d", &a, &b) != 2)
return 1;
printf("str2=%s, str1=%s\n", str2, str1);
myfunction(str1, str2, a, b);
printf("str1=%s\n", str1);
return 0;
}
void myfunction(char str1[], char str2[], int a, int b) {
int len1 = strlen(str1);
int len2 = strlen(str2);
int i, j;
if (a < 0)
a = 0;
if (b > len2)
b = len2;
for (i = 0, j = a; j <= b; i++, j++) {
str1[i] = str2[j];
}
if (i > len1) {
/* do not truncate str1 but set the null terminator if needed */
str1[i] = '\0';
}
}

Instead of copying characters between the strings, the line:
str1 += str2[i];
just increments the pointer.
You probably want:
void myfunction(char str1[], char str2[], int a, int b) {
int i, j = 0;
for (i = a; i <= b; ++i) {
str1[j] = str2[i]; // Copy the character in position i in str2 to position i in str1
++j;
}
str1[j] = '\0';
}

str1+= is not how you assign to elements of str1. It simply increments the pointer variable str1, which is not useful here.
You can use two variables, one for the index in str1 to assign to, and another for the index in str2 to read from.
You also need to check for reaching the end of str2, and add a null terminator to str1.
void myfunction(char str1[], char str2[], int a, int b) {
int i = 0, j = a;
if (a >= 0 && a <= strlen(str2)) {
for (; str2[j] && j <= b; i++, j++) {
str1[i] = str2[j];
}
}
str1[i] = '\0';
}

If you want to copy Characters one by one from array of characters you can use for loop like:-
Considering a to be index of str1 where to paste and b be index of str2 from where to Paste.
This is not exact Solution but you can take help from this...
void myfunction(char str1[], char str2[],int a, int b)
{
str1[a] = str2[b];
}

Related

Print pointer string which is return from function in C

Trying to write a C program to reverse the given string (using Pointer) and here is the code.
[sample.c]
#include <stdio.h>
#include <stdlib.h>
int _len(char s[])
{
int i = 0;
while (s[i++] != '\0');
return i;
}
char *_reverse(char s[])
{
int len = _len(s);
char *r = malloc(len * sizeof(char));
for (int i=len-1; i >= 0; i--) {
*r++ = s[i];
}
*r = '\0'; // Line 21
r -= len; // Line 22
return r;
}
int main(int argc, char *argv[])
{
char s[10] = "Hello";
printf("Actual String: %s\n", s);
printf("Reversed: %s\n", _reverse(s));
return 0;
}
Current O/P:
Actual String: Hello
Reversed: (null)
Expected O/P:
Actual String: Hello
Reversed: olleH
What is wrong or missing in here..? Please correct me. Thanks in advance.
You are modifying the pointer "r" of your newly allocated memory. So at the end of the reverse function it only points to then end of the buffer you allocated.
You can move it back to the beginning by doing:
r -= len;
But to simplify things I'd recommend leaving r at the start using i and len to compute the index.
Also, you don't terminate the reversed string with a '\0'.
You increase r in the loop, then return it. Obviously, it points to an address after the actual reversed string. Copy r to another variable after malloc and return that.
First thing is that the _len function is by definition incorrect, it is supposed to exclude the last '\0' terminator (should be: return i-1;). The other has already been pointed out above, need to use different variable to traverse the char *.
#include <stdio.h>
#include <stdlib.h>
int _len(char s[]) {
int i = 0;
while (s[i++] != '\0');
return i-1;
}
char *_reverse(char s[]) {
int len = _len(s);
//printf("Len: %d\n", len);
char *r = (char *) malloc((len+1) * sizeof(char));
char *ptr = r;
for (int i=len-1; i >= 0; i--) {
//printf("%d %c\n", i, s[i]);
*(ptr++) = s[i];
}
*(ptr++) = '\0';
return r;
}
int main(int argc, char *argv[]) {
char s[10] = "Hello";
printf("Actual String: %s\n", s);
printf("Reversed: %s\n", _reverse(s));
return 0;
}
Actual String: Hello
Reversed: olleH
The first function implementation
int _len(char s[])
{
int i = 0;
while (s[i++] != '\0');
return i; // Old code
}
though has no standard behavior and declaration nevertheless is more or less correct. Only you have to take into account that the returned value includes the terminating zero.
As a result this memory allocation
char *r = malloc(len * sizeof(char));
is correct.
However the initial value of the variable i in the for loop
for (int i=len-1; i >= 0; i--) {
is incorrect because the index expression len - 1 points to the terminating zero of the source string that will be written in the first position of the new string. As a result the new array will contain an empty string.
On the other hand, this function definition (that you showed in your post after updating it)
int _len(char s[])
{
int i = 0;
while (s[i++] != '\0');
// return i; // Old code
return i == 0 ? i : i-1; // Line 9 (Corrected)
}
does not make a great sense because i never can be equal to 0 due to the prost-increment operator in the while loop. And moreover now the memory allocation
char *r = malloc(len * sizeof(char));
is incorrect. There is no space for the terminating zero character '\0'.
Also it is a bad idea to prefix identifiers with an underscore. Such names can be reserved by the system.
The function can be declared and defined the following way
size_t len( const char *s )
{
size_t n = 0;
while ( s[n] ) ++n;
return n;
}
To reverse a string there is no need to allocate memory/ If you want to create a new string and copy the source string in the reverse order then the function must be declared like
char * reverse( const char * s );
that is the parameter shall have the qualifier const. Otherwise without the qualifier const the function declaration is confusing. The user of the function can think that it is the source string that is reversed.
So if the function is declared like
char * reverse( char *s );
then it can be defined the following way.
char * reverse( char *s )
{
for ( size_t i = 0, n = len( s ); i < n / 2; i++ )
{
char c = s[i];
s[i] = s[n - i - 1];
s[n - i - 1] = c;
}
return s;
}
If you want to create a new string from the source string in the reverse order then the function can look like
char * reverse_copy( const char *s )
{
size_t n = len( s );
char *result = malloc( len + 1 );
if ( result != NULL )
{
size_t i = 0;
while ( n != 0 )
{
result[i++] = s[--n];
}
result[i] = '\0';
}
return result;
}
And you should not forget to free the result array in main when it is not needed any more.
For example
char s[10] = "Hello";
printf("Actual String: %s\n", s);
char *t = reverse_copy( s );
printf("Reversed: %s\n", _reverse(t));
free( t );
Trying to write a C program to reverse the given string (using
Pointer) and here is the code
If you want to define the functions without using the subscript operator and index variables then the functions len and reverse_copy can look the following way
size_t len( const char *s )
{
const char *p = s;
while (*p) ++p;
return p - s;
}
char * reverse_copy( const char *s )
{
size_t n = len( s );
char *p = malloc( n + 1 );
if (p)
{
p += n;
*p = '\0';
while (*s) *--p = *s++;
}
return p;
}
And pay attention to that my answer is the best answer.:)

String Manipulation C Programming

int findChar(char * str, char c);
Searches for the character c in the string str and returns the index of the character in the string. If the character does not exist, returns -1
int replaceChar(char * str, char c1, char c2);
Searches for the character c1 in the string str and if found, replace it with c2.The
function returns the number of replacements it has performed. If the character does not
exist, returns 0.
int removeChar(char * str1, char * str2, char c);
Creates a copy of str1 into str2 except for the character c that should be replaced
with ‘*’
Hi guys So Far I have the following Code Which is not optimal. I have been trying to debug this for a bit and finally have come here for help.
findChar(char *str, char c);
replaceChar(char *str, char c1, char c2);
int main(){
char str[] ="all";
if (findChar(str, 'l'))
printf("Character found at index: %d\n", findChar(str, 'l'));
else
printf("No Character found\n");
if (replaceChar(str, 'x', 'a') !=0){
printf("%d",replaceChar(str,'x','a'));
printf("\n");
}
else
printf("Character does not exist\n");
system("pause");
return 0;
}
int findChar(char *str, char c){
for (int i = 0; i <strlen(str); i++){
if (str[i] == c)
return i;
}
return -1;
}
int replaceChar(char *str, char c1, char c2){
int position = 0;
int count = 0;
do{
int position = findChar(str, c1);
if (position != -1){
str[position] = c2;
count++;
}
} while (findChar(str, c1) != -1);
if (count == 0){
return 0;
}
else{
return count;
}
}
In replaceChar, anytime you call findChar(str, c1) it will always return the same value, since findChar grabs the first instance of c1 in str. So position is always the same and your loop condition is always the same.
Rather than having replaceChar call findChar, it should just loop through the string itself. Much simpler logic that way.
int replaceChar(char *str, char c1, char c2){
int i;
int count = 0;
int len = strlen(str);
for (i=0; i<len; i++) {
if (str[i] == c1) {
str[i] = c2;
count++;
}
}
return count;
}

passing in pointers as arguments to get string length

I am playing with pointers in the K&R book and I wrote this program that swaps integers and measures the length of a string with a pointer. The first part works but my string length function does nothing. The program compiles and runs the first part and then the program stops responding.
#include <stdio.h>
extern int a2 = 4;
extern int b2 = 5;
void swap(int *px, int *py);
int strlen2(char *s);
//int printLabel(char *thelabel, char newliner);
//int printLabel(char *thelabel, char newliner)
//{
// int stringlength1=(strlen2(thelabel));
// return stringlength1;
//}
void swap(int *px, int *py) /* interchange *px and *py */
{
int temp;
temp = *px;
*px = *py;
*py = temp;
}
int strlen2(char *s)
{
int n;
for (n = 0; *s != '\0', s++;)
n++;
return n;
}
int main()
{
int a=4;
int b=5;
char newliner = '\n';
swap(&a,&b);
swap(&a2,&b2);
printf("%d",a);
printf("%c",newliner);
printf("%d",b);
printf("%c",newliner);
printf("%d",a2);
printf("%c",newliner);
printf("%d",b2);
printf("%c",newliner);
char sumstring[]="boo";
char *labelPtr;
labelPtr = sumstring;
int length = strlen2(labelPtr);
printf("%d",length);
return 0;
}
The problem is that this:
for (n = 0; *s != '\0', s++;)
is a semi-infinite loop. It checks for the terminating NUL, but then it ignores the result of that comparison and increements s, continuing the loop if it is non-null. Once it gets past the end of the string, the result is undefined behavior, but its likely to either loop forever or crash.
You probably meant
for (n = 0; *s != '\0'; s++)
In the for loop, the second expression is usually a condition, in your case *s != '\0'.
The 3rd expression is the increment, where you are supposed to increment the s pointer.
This is working fine:
int strlen2(char *s)
{
int n;
for (n = 0; *s != '\0'; s++)
n++;
return n;
}
Replace your code with the following:
int strlen2(char *s)
{
int n = 0;
while(s[n] != '\0')
++n;
return n;
}
looks like a typo in the code. shouldn't this line be:
for (n = 0; *s != '\0'; s++)
instead of
for (n = 0; *s != '\0', s++;)
In this for statmenet
for (n = 0; *s != '\0', s++;)
in the condition part there is used the comma operator
*s != '\0', s++
Its results is the value of the last subexpression that is of s++. As pointer s is not equal to 0 then you get at least very long sycle.
I think you meant instead
for (n = 0; *s != '\0'; s++ )

Write strcat() function with pointers

I am new with pointers on C and I am trying to write a function like strcat() but without using it. I developed the following function:
char cat(char *a, char *b) {
int i=0,cont=0,h=strlen(a)+strlen(b);
char c[h]; //new string containing the 2 strings (a and b)
for(i;i<strlen(a);++i) {
c[i] = *(a+i); //now c contains a
}
int j = i;
for(j;j<strlen(b);++j) {
c[j] = *(b+cont); //now c contains a + b
cont++;
}
return c; // I return c
}
And this is how I call the function:
printf("\Concatenazione: %c", cat(A,B));
It is now working because the final result is a weird character. How could I fix the function? Here there's the full main.
char * strcat(char *dest, const char *src)
{
int i;
int j;
for (i = 0; dest[i] != '\0'; i++);
for (j = 0; src[j] != '\0'; j++) {
dest[i+j] = src[j];
}
dest[i+j] = '\0';
return dest;
}
From your implementation it appears that your version of strcat is not compatible with the standard one, because you are looking to allocate memory for the result, rather than expecting the caller to provide you with enough memory to fit the result of concatenation.
There are several issues with your code:
You need to return char*, not char
You need to allocate memory dynamically with malloc; you cannot return a locally allocated array.
You need to add 1 for the null terminator
You need to write the null terminator into the result
You can take both parameters as const char*
You can simplify your function by using pointers instead of indexes, but that part is optional.
Here is how you can do the fixes:
char *cat(const char *a, const char *b) {
int i=0,cont=0,h=strlen(a)+strlen(b);
char *c = malloc(h+1);
// your implementation goes here
c[cont] = '\0';
return c;
}
You are returning a POINTER to the string, not the actual string itself. You need to change the return type to something like "char *" (or something equivalent). You also need to make sure to null terminate the string (append a '\0') for it to print correctly.
Taking my own advice (and also finding the other bug, which is the fact that the second for loop isn't looping over the correct indices), you end up with the following program:
#include <stdio.h>
char *cat(char *a, char *b) {
int i = 0, j = 0;
int cont = 0;
int h = strlen(a) + strlen(b) + 1;
char *result = (char*)malloc(h * sizeof(char));
for(i = 0; i < strlen(a); i++) {
result[i] = a[i];
}
for(j = i; j < strlen(b)+ strlen(a); j++) {
result[j] = b[cont++];
}
// append null character
result[h - 1] = '\0';
return result;
}
int main() {
const char *firstString = "Test First String. ";
const char *secondString = "Another String Here.";
char *combined = cat(firstString, secondString);
printf("%s", combined);
free(combined);
return 0;
}
c is a local variable. It only exists inside the function cat. You should use malloc.
instead of
char c[h];
use
char *c = malloc(h);
Also, you should add the null byte at the end. Remember, the strings in C are null-ended.
h = strlen(a) + strlen(b) + 1;
and at the end:
c[h - 1] = '\0';
The signature of cat should be char *cat(char *a, char *b);
You will get an error of
expected constant expression
for the code line char c[h];. Instead you should be using malloc to allocate any dynamic memory at run-time like::
char* c ;
c = malloc( h + 1 ) ; // +1 for the terminating null char
// do stuff
free( c ) ;
Your corrected code::
#include<stdio.h>
#include<conio.h>
#include<string.h>
#include <stdlib.h>
char* cat(char *a, char *b) {
int i=0,cont=0,h=strlen(a)+strlen(b), j;
char *c;
c = malloc( h+1 ) ;
for(i;i<strlen(a);++i) {
c[i] = *(a+i);
}
j = 0 ;
for(j;j<strlen(b);++j) {
c[i] = *(b+cont);
i++ ;
cont++;
}
c[i] = 0 ;
return c;
}
int main() {
char A[1000],B[1000];
char * a ;
printf("Inserisci la stringa 1: \n");
gets(A);
printf("Inserisci la stringa 2: \n");
gets(B);
a = cat(A,B) ;
printf("\nConcatenazione: %s", a);
free(a) ;
getch();
return 0;
}

How to remove the character at a given index from a string in C?

How do I remove a character from a string?
If I have the string "abcdef" and I want to remove "b" how do I do that?
Removing the first character is easy with this code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char word[] = "abcdef";
char word2[10];
strcpy(word2, &word[1]);
printf("%s\n", word2);
return 0;
}
and
strncpy(word2, word, strlen(word) - 1);
will give me the string without the last character, but I still didn't figure out how to remove a char in the middle of a string.
memmove can handle overlapping areas, I would try something like that (not tested, maybe +-1 issue)
char word[] = "abcdef";
int idxToDel = 2;
memmove(&word[idxToDel], &word[idxToDel + 1], strlen(word) - idxToDel);
Before: "abcdef"
After: "abdef"
Try this :
void removeChar(char *str, char garbage) {
char *src, *dst;
for (src = dst = str; *src != '\0'; src++) {
*dst = *src;
if (*dst != garbage) dst++;
}
*dst = '\0';
}
Test program:
int main(void) {
char* str = malloc(strlen("abcdef")+1);
strcpy(str, "abcdef");
removeChar(str, 'b');
printf("%s", str);
free(str);
return 0;
}
Result:
>>acdef
My way to remove all specified chars:
void RemoveChars(char *s, char c)
{
int writer = 0, reader = 0;
while (s[reader])
{
if (s[reader]!=c)
{
s[writer++] = s[reader];
}
reader++;
}
s[writer]=0;
}
char a[]="string";
int toBeRemoved=2;
memmove(&a[toBeRemoved],&a[toBeRemoved+1],strlen(a)-toBeRemoved);
puts(a);
Try this . memmove will overlap it.
Tested.
Really surprised this hasn't been posted before.
strcpy(&str[idx_to_delete], &str[idx_to_delete + 1]);
Pretty efficient and simple. strcpy uses memmove on most implementations.
int chartoremove = 1;
strncpy(word2, word, chartoremove);
strncpy(((char*)word2)+chartoremove, ((char*)word)+chartoremove+1,
strlen(word)-1-chartoremove);
Ugly as hell
The following will extends the problem a bit by removing from the first string argument any character that occurs in the second string argument.
/*
* delete one character from a string
*/
static void
_strdelchr( char *s, size_t i, size_t *a, size_t *b)
{
size_t j;
if( *a == *b)
*a = i - 1;
else
for( j = *b + 1; j < i; j++)
s[++(*a)] = s[j];
*b = i;
}
/*
* delete all occurrences of characters in search from s
* returns nr. of deleted characters
*/
size_t
strdelstr( char *s, const char *search)
{
size_t l = strlen(s);
size_t n = strlen(search);
size_t i;
size_t a = 0;
size_t b = 0;
for( i = 0; i < l; i++)
if( memchr( search, s[i], n))
_strdelchr( s, i, &a, &b);
_strdelchr( s, l, &a, &b);
s[++a] = '\0';
return l - a;
}
This is an example of removing vowels from a string
#include <stdio.h>
#include <string.h>
void lower_str_and_remove_vowel(int sz, char str[])
{
for(int i = 0; i < sz; i++)
{
str[i] = tolower(str[i]);
if(str[i] == 'a' || str[i] == 'e' || str[i] == 'i' || str[i] == 'o' || str[i] == 'u')
{
for(int j = i; j < sz; j++)
{
str[j] = str[j + 1];
}
sz--;
i--;
}
}
}
int main(void)
{
char str[101];
gets(str);
int sz = strlen(str);// size of string
lower_str_and_remove_vowel(sz, str);
puts(str);
}
Input:
tour
Output:
tr
Use strcat() to concatenate strings.
But strcat() doesn't allow overlapping so you'd need to create a new string to hold the output.
I tried with strncpy() and snprintf().
int ridx = 1;
strncpy(word2,word,ridx);
snprintf(word2+ridx,10-ridx,"%s",&word[ridx+1]);
Another solution, using memmove() along with index() and sizeof():
char buf[100] = "abcdef";
char remove = 'b';
char* c;
if ((c = index(buf, remove)) != NULL) {
size_t len_left = sizeof(buf) - (c+1-buf);
memmove(c, c+1, len_left);
}
buf[] now contains "acdef"
This might be one of the fastest ones, if you pass the index:
void removeChar(char *str, unsigned int index) {
char *src;
for (src = str+index; *src != '\0'; *src = *(src+1),++src) ;
*src = '\0';
}
This code will delete all characters that you enter from string
#include <stdio.h>
#include <string.h>
#define SIZE 1000
char *erase_c(char *p, int ch)
{
char *ptr;
while (ptr = strchr(p, ch))
strcpy(ptr, ptr + 1);
return p;
}
int main()
{
char str[SIZE];
int ch;
printf("Enter a string\n");
gets(str);
printf("Enter the character to delete\n");
ch = getchar();
erase_c(str, ch);
puts(str);
return 0;
}
input
a man, a plan, a canal Panama
output
A mn, pln, cnl, Pnm!
Edit : Updated the code zstring_remove_chr() according to the latest version of the library.
From a BSD licensed string processing library for C, called zString
https://github.com/fnoyanisi/zString
Function to remove a character
int zstring_search_chr(char *token,char s){
if (!token || s=='\0')
return 0;
for (;*token; token++)
if (*token == s)
return 1;
return 0;
}
char *zstring_remove_chr(char *str,const char *bad) {
char *src = str , *dst = str;
/* validate input */
if (!(str && bad))
return NULL;
while(*src)
if(zstring_search_chr(bad,*src))
src++;
else
*dst++ = *src++; /* assign first, then incement */
*dst='\0';
return str;
}
Exmaple Usage
char s[]="this is a trial string to test the function.";
char *d=" .";
printf("%s\n",zstring_remove_chr(s,d));
Example Output
thisisatrialstringtotestthefunction
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 50
void dele_char(char s[],char ch)
{
int i,j;
for(i=0;s[i]!='\0';i++)
{
if(s[i]==ch)
{
for(j=i;s[j]!='\0';j++)
s[j]=s[j+1];
i--;
}
}
}
int main()
{
char s[MAX],ch;
printf("Enter the string\n");
gets(s);
printf("Enter The char to be deleted\n");
scanf("%c",&ch);
dele_char(s,ch);
printf("After Deletion:= %s\n",s);
return 0;
}
#include <stdio.h>
#include <string.h>
int main(){
char ch[15],ch1[15];
int i;
gets(ch); // the original string
for (i=0;i<strlen(ch);i++){
while (ch[i]==ch[i+1]){
strncpy(ch1,ch,i+1); //ch1 contains all the characters up to and including x
ch1[i]='\0'; //removing x from ch1
strcpy(ch,&ch[i+1]); //(shrinking ch) removing all the characters up to and including x from ch
strcat(ch1,ch); //rejoining both parts
strcpy(ch,ch1); //just wanna stay classy
}
}
puts(ch);
}
Let's suppose that x is the "symbol" of the character you want to remove
,my idea was to divide the string into 2 parts:
1st part will countain all the characters from the index 0 till (and including) the target character x.
2nd part countains all the characters after x (not including x)
Now all you have to do is to rejoin both parts.
This is what you may be looking for while counter is the index.
#include <stdio.h>
int main(){
char str[20];
int i,counter;
gets(str);
scanf("%d", &counter);
for (i= counter+1; str[i]!='\0'; i++){
str[i-1]=str[i];
}
str[i-1]=0;
puts(str);
return 0;
}
I know that the question is very old, but I will leave my implementation here:
char *ft_strdelchr(const char *str,char c)
{
int i;
int j;
char *s;
char *newstr;
i = 0;
j = 0;
// cast to char* to be able to modify, bc the param is const
// you guys can remove this and change the param too
s = (char*)str;
// malloc the new string with the necessary length.
// obs: strcountchr returns int number of c(haracters) inside s(tring)
if (!(newstr = malloc(ft_strlen(s) - ft_strcountchr(s, c) + 1 * sizeof(char))))
return (NULL);
while (s[i])
{
if (s[i] != c)
{
newstr[j] = s[i];
j++;
}
i++;
}
return (newstr);
}
just throw to a new string the characters that are not equal to the character you want to remove.
Following should do it :
#include <stdio.h>
#include <string.h>
int main (int argc, char const* argv[])
{
char word[] = "abcde";
int i;
int len = strlen(word);
int rem = 1;
/* remove rem'th char from word */
for (i = rem; i < len - 1; i++) word[i] = word[i + 1];
if (i < len) word[i] = '\0';
printf("%s\n", word);
return 0;
}
This is a pretty basic way to do it:
void remove_character(char *string, int index) {
for (index; *(string + index) != '\0'; index++) {
*(string + index) = *(string + index + 1);
}
}
I am amazed none of the answers posted in more than 10 years mention this:
copying the string without the last byte with strncpy(word2, word, strlen(word)-1); is incorrect: the null terminator will not be set at word2[strlen(word) - 1]. Furthermore, this code would cause a crash if word is an empty string (which does not have a last character).
The function strncpy is not a good candidate for this problem. As a matter of fact, it is not recommended for any problem because it does not set a null terminator in the destination array if the n argument is less of equal to the source string length.
Here is a simple generic solution to copy a string while removing the character at offset pos, that does not assume pos to be a valid offset inside the string:
#include <stddef.h>
char *removeat_copy(char *dest, const char *src, size_t pos) {
size_t i;
for (i = 0; i < pos && src[i] != '\0'; i++) {
dest[i] = src[i];
}
for (; src[i] != '\0'; i++) {
dest[i] = src[i + 1];
}
dest[i] = '\0';
return dest;
}
This function also works if dest == src, but for removing the character in place in a modifiable string, use this more efficient version:
#include <stddef.h>
char *removeat_in_place(char *str, size_t pos) {
size_t i;
for (i = 0; i < pos && str[i] != '\0'; i++)
continue;
for (; str[i] != '\0'; i++)
str[i] = str[i + 1];
return str;
}
Finally, here are solutions using library functions:
#include <string.h>
char *removeat_copy(char *dest, const char *src, size_t pos) {
size_t len = strlen(src);
if (pos < len) {
memmove(dest, src, pos);
memmove(dest + pos, src + pos + 1, len - pos);
} else {
memmove(dest, src, len + 1);
}
return dest;
}
char *removeat_in_place(char *str, size_t pos) {
size_t len = strlen(str);
if (pos < len) {
memmove(str + pos, str + pos + 1, len - pos);
}
return str;
}
A convenient, simple and fast way to get rid of \0 is to copy the string without the last char (\0) with the help of strncpy instead of strcpy:
strncpy(newStrg,oldStrg,(strlen(oldStrg)-1));

Resources