string manipulate

This is a discussion on string manipulate within the C Programming forums, part of the General Programming Boards category; I want to take all of a specific letter from a string and insert another letter were the old ones ...

  1. #1
    Registered User
    Join Date
    Jul 2008
    Location
    Fort Worth TX
    Posts
    15

    string manipulate

    I want to take all of a specific letter from a string and insert another letter were the old ones were i just cant figure out how.For example say you enter the string "goodbye" and i want to change all the o's to a's how would i do that?

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    23,820
    Loop over the characters of the string. Whenever the current character is an 'o', assign an 'a'.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Mar 2008
    Posts
    43
    Here's an example:

    Code:
    #include <stdio.h>
    #include <string.h>
    
    int main(void)
    {
    	char str[] = "goodbye";
    	int str_len = strlen(str);
    	int x;
    
    	printf("BEFORE: %s\n", str);
    
    	for(x = 0; x < str_len; x++)
    	{
    		if(str[x] == 'o')
    			str[x] = 'a';
    	}
    		
    	printf("AFTER: %s\n", str);
    	
    	return 0;	 
    }

  4. #4
    Registered User
    Join Date
    Jul 2008
    Posts
    5
    Another way to loop over a string using the fact that c strings are Null terminated:
    Code:
    for (i = 0;str[i] != '\0';++i) ;
    And it retains the "spirit of the language" which strlen() does not.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. String Class
    By BKurosawa in forum C++ Programming
    Replies: 117
    Last Post: 08-09-2007, 01:02 AM
  2. String issues
    By The_professor in forum C++ Programming
    Replies: 7
    Last Post: 06-12-2007, 09:11 AM
  3. Classes inheretance problem...
    By NANO in forum C++ Programming
    Replies: 12
    Last Post: 12-09-2002, 02:23 PM
  4. creating class, and linking files
    By JCK in forum C++ Programming
    Replies: 12
    Last Post: 12-08-2002, 01:45 PM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21