Thread: Help! Remove a char in a string

  1. #1
    Registered User
    Join Date
    Oct 2003
    Posts
    2

    Help! Remove a char in a string

    I need to remove all 'a'' from a string.

    For example,
    String = "apple and orange"
    =>String = "pple nd ornge"

    That's what I did in Java
    Code:
    for (int i=0;i<sentence.length();i++){
     if (sentence.charAt(i)=='a'){
      sentence =  sentence.substring(0,i)+sentence.substring(i+1);    }
    But how to convert this Java code into C code?

    I am new to C, can anyone help me on this code?

    thanks

  2. #2
    Just Lurking Dave_Sinkula's Avatar
    Join Date
    Oct 2002
    Posts
    5,005
    Build a new string one character at a time.
    Code:
    #include <stdio.h>
    
    int main ( void )
    {
       const char text[] = "apple and orange";
       char result[ sizeof text ];
       int i, j = 0;
       for ( i = 0; text[i] != '\0'; ++i )
       {
          if ( text[i] != 'a' )
          {
             result[j++] = text[i];
          }
       }
       result[j] = '\0';
       puts(result);
       return 0;
    }
    
    /* my output
    pple nd ornge
    */
    7. It is easier to write an incorrect program than understand a correct one.
    40. There are two ways to write error-free programs; only the third one works.*

  3. #3
    Registered User
    Join Date
    Oct 2003
    Posts
    49
    Code:
    char sentence[]="apple and oranges";
    int i,j;
    
    for(i=0; i<strlen(sentence); i++) {
       if(sentence[i]=='a')
          for(j=i; j<strlen(sentence); j++) sentence[j]=sentence[j+1];
    }
    edit: I was too slow again

  4. #4
    Registered User
    Join Date
    Oct 2003
    Posts
    2
    Thank you, Dave_Sinkula & DrZoidberg.

    You help me a lots.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  2. Inheritance Hierarchy for a Package class
    By twickre in forum C++ Programming
    Replies: 7
    Last Post: 12-08-2007, 04:13 PM
  3. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  4. String Manipulation problems -_-
    By Astra in forum C Programming
    Replies: 5
    Last Post: 12-13-2006, 05:48 PM
  5. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM