Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,888 questions

51,815 answers

573 users

How to remove the last occurrence of a character from a string in C

2 Answers

0 votes
#include <stdio.h>
#include <string.h>
    
void remove_last_occurrences(char str[], char ch) {
    int len = strlen(str), lastIndexOf_c = -1;
    
    for (int i = 0; i < len; i++){
        if (str[i] == ch) {
            lastIndexOf_c = i;
        }
    }
    if (lastIndexOf_c != -1) {
        memmove(str + lastIndexOf_c, str + lastIndexOf_c + 1, len - lastIndexOf_c + 1);
    }
}

int main() {
    char str[64] = "c python c++ c# java";
    
    remove_last_occurrences(str, 'c');

    puts(str);
 
    return 0;
}


          
/*
run:
       
c python c++ # java

*/

 



answered Jun 13, 2022 by avibootz
edited Sep 8, 2024 by avibootz
0 votes
#include <stdio.h>
#include <string.h>
   
void remove_last_occurrences(char s[], char ch) {
    int i  = 0, last = -1;
    while(s[i]) {
        if(s[i] == ch) {
            last = i;
        }
        i++;
    }
    if (last == -1) return;
     
    i = last;
    int len = strlen(s);
    while(i < len) {
        s[i] = s[i + 1];
        i++;
    }
}
   
int main() {
    char s[] = "c c++ c# java php python cobol";
  
    remove_last_occurrences(s, 'p');
    puts(s);
     
    remove_last_occurrences(s, 'p');
    puts(s);
     
    remove_last_occurrences(s, 'x');
    puts(s);
       
    return 0;
}
    
    
         
/*
run:
      
c c++ c# java php ython cobol
c c++ c# java ph ython cobol
c c++ c# java ph ython cobol
   
*/

 



answered Sep 8, 2024 by avibootz

Related questions

...