Problem with strings.

I wanted to write a function that returns string without characters between first and last small letters 'a'. Function returns wanted output, but in main it prints out some nonsense. What could be wrong?
Thanks in advance.

Expected:
input: basketball
output: baall

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
  #include<ctype.h>
  #include<string.h>
  #include<iostream>
  #define _CRT_SECURE_NO_WARNINGS
  using namespace std;

  char* remove(char str[])
  {
	char sp1[80], sp2[80];
	strncpy_s(sp1, str, strchr(str, 'a') - str + 1);
	sp1[strchr(str, 'a') - str + 1] = '\0';
	strcpy_s(sp2, str + (strrchr(str, 'a') - str));
	strcat_s(sp1, sp2);
	return sp1;
  }

  int main()
  {
	char s[80];
	gets_s(s);
	puts(remove(s));
	system("pause");
	return 0;
  }
Last edited on
Are you writing in C or C++?

Or just whatever happens to compile?
it's C++.
Right, so write it in C++ then.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
  //!! Nope #include<ctype.h>
  //!! Nope #include<string.h>
  #include<iostream>
  #include <string>
  //!! Nope #define _CRT_SECURE_NO_WARNINGS
  using namespace std;

  string remove(const string &str)
  {
      string result;
      // some code here
      return result;
  }

  int main()
  {
	string s;
        getline(cin,s);
        cout << remove(s) << endl;
	system("pause");
	return 0;
  }
there may be better ways, but one easy to follow way would be to iterate the string forward, looking for 'a', and saving the index in the string where that is.
Then do it in reverse, and save it again.
If you found an a (its ok if you found the same one twice) proceed, else return original string. Proceed, you want to pull the substrings from 0 to first a and from a to end of string, and concatenate those, return that. This will eliminate the letter a if only one a is found, is that desired? If not, you can return if the first and last a are the same index instead. It can be done more efficiently of course, this is the simple approach.
Last edited on
Topic archived. No new replies allowed.