#include <iostream.h>
#include <string>
int main()
{
char cString[64];
cout << "Enter a string: ";
cin.getline(cString, sizeof(cString));
char cK = ''k'';
char* pcK = &cK
while(strchr(cString, ''y''))
{
strcpy(strchr(cString, ''y''), pcK);
}
cout << endl << cString << endl;
return 0;
}
Replace part of a string?
Another newbie question:
I''m trying to replace every letter ''y'' in a string with the letter ''k''. Here''s my code:
Right now what happens is it will replace the first letter ''y'' with the letter ''k'', but everything after that first ''y'' won''t be outputted at the end. For example, if I enter ''my house'' it will output ''mk'' and leave off the rest of the string.
Anyway, thanks for your help guys. I''m not experienced with pointers so that may be part of my problem.
Shmiznac
Shmiznac
Please stop mixing C and C++. It results in disgusting code.
C++:
C:
[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!
C++:
#include <iostream>#include <string>using namespace std;int main(){ string str; cout << "Enter a string: "; getline(cin, str); int pos = 0; while(pos != string::npos) { pos = str.find_fist_of("k", pos); str[pos] = ''y''; } cout << ''\n'' << str << endl;}
C:
#include <stdio.h>#include <string.h>int main(){ char str[256]; ptrinf("Enter a string: "); scanf("%s", str); char *pos = &str[0]; while(pos) { pos = strchr(pos, ''k''); *pos = ''y''; } printf("%s", str); return 0;}
[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!
#include <string>#include <algorithm>using namespace std;char y_to_k( char c ){ if(c == ''y'') return ''k''; else return c;}int main(){ string s = ...; transform(s.begin(), s.end(), s.begin(), y_to_k);}
Neat! I need to get up on my <algorithm>
[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!
[ GDNet Start Here | GDNet Search Tool | GDNet FAQ | MS RTFM [MSDN] | SGI STL Docs | Google! ]
Thanks to Kylotan for the idea!
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement