![]() |
| | #1 |
| Registered User Join Date: Sep 2009
Posts: 68
| Using .find and .replace with strings Here is the code that does the conversion.. Essentially i have a string like... C++ is awesome! it must convert C++ to java. then it converts all letters to Uppercase I have it working with there is one instance of C++, however if there is none or more than one it will not work proper. Im figured i need to do some kind of loop that goes through checking for C++ and changing it if it finds it .... not sure how exactly to do that Code: modified = original;
pos = original.find("C++");
modified.replace(pos,3,"java");
upperStr = modified;
int i = 0;
while (i<modified.length())
{
if (modified[i] == ' ' || modified[i] == ',' || modified[i] == '.')
{
upperStr[i] = modified[i];
}
if (modified[i] >= 65 && modified[i] <= 90)
{
upperStr[i] = modified[i] + 32;
}
if (modified[i] >= 97 && modified[i] <= 122)
{
upperStr[i] = modified[i] - 32;
}
i++;
}
|
| bleuz is offline | |
| | #2 |
| and the hat of sweating Join Date: Aug 2007 Location: Toronto, ON
Posts: 3,425
| Code: if (modified[i] >= 65 && modified[i] <= 90)
{
upperStr[i] = modified[i] + 32;
}
if (modified[i] >= 97 && modified[i] <= 122)
{
upperStr[i] = modified[i] - 32;
}
__________________ "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008 "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010 |
| cpjust is offline | |
| | #3 |
| Registered User Join Date: Sep 2009
Posts: 68
| Yes i agree with you however we are not able to use the header file needed for those functions |
| bleuz is offline | |
| | #4 |
| Registered User Join Date: Sep 2009
Posts: 68
| anymore advice would be appreciated |
| bleuz is offline | |
| | #5 |
| Registered User Join Date: Jan 2005
Posts: 7,278
| Instead of using numbers like 65 and 97, use the character literals like 'A' and 'Z'. It works the same, and it is much clearer to the person reading the code. As to your find/replace question, you need to use a loop. Keep calling find and checking the return value. If find returns a valid position, use it to perform the replace. Then use that position as the starting point for your next call to find so that you don't keep looking over the same text over and over. When find doesn't find anything, end your loop. I believe find returns string::npos (which is basically -1) when it can't find the text, but you should verify that first. |
| Daved is offline | |
![]() |
| Thread Tools | |
| Display Modes | |
|