简体   繁体   中英

Getting the middle character of a string. Two characters in the middle if length is even

Write a function that returns a string containing the middle character in str if the length of str is odd, or the two middle characters if the length is even. For example, middle("middle") returns "dd".

The code is written as such:

#include <iostream>
#include <string.h>
using namespace std;

int main() {
 string word;
 int length;

 cout << "Enter string: ";
 cin >> word;

 length = word.length();

 if ((word.length() % 2) == 1){
  cout << word.substr(length / 2);
 }
 if ((word.length() % 2) == 0){
  cout << word.substr((length / 2), (length / 2) + 1);
 }
}

I ran it, and the problem was that while testing with string "middle" , it would return "dle" instead of "dd" . word.substr((length / 2), (length / 2) + 1); this part seems to be correct, but why does it output such an answer?

An alternative to @Remy's answer (without if):

    cout << word.substr((length-1) / 2, 2 - length%2);

For starters you have to include the header <string> where the standard class std::string is declared. The header <string.h> has to be removed.

For a string with an even number of elements the middle of the string is calculated incorrectly. The same problem exists with the calculation of the number of elements that to be extracted from a string independent of the number of elements in it.

The program can look for example the following way.

#include <iostream>
#include <string>

int main() 
{
    std::string s;
    
    std::cout << "Enter string: ";
    std::cin >> s;

    auto pos = s.length() == 0 ? 0 : s.length() / 2 - ( s.length() % 2 == 0 );
    auto n = 1 + ( s.length() % 2 == 0 );
    
    std::cout << s.substr( pos, n ) << '\n';
    
    return 0;
}

For different inputs the program output can look the following way

Enter string: a
a

Enter string: ab
ab

Enter string: abc
b

Enter string: abcd
bc

Enter string: middle
dd

Pay attention that the user can interrupt the input. In this case you will have an empty string. Such a string should be processed correctly.

You are using the std::string::substr() method incorrectly.

When calling substr() with 1 parameter, it takes a starting index , and will return all remaining characters up to the end of the string. That is not what you want in this case. You need to specify the number of characters to return, which for an odd-lengthed string is 1.

When calling substr() with 2 parameters, it takes a starting index and a count of characters , not a range of indexes as you have coded it. For an even-lengthed string, you are specifying both the wrong index and the wrong count. You need to subtract 1 from the index, and specify the number of characters as 2.

Try something more like this instead:

#include <iostream>
#include <string>
using namespace std;

int main() {
    string word;

    cout << "Enter string: ";
    if (cin >> word) {
        string::size_type length = word.length();
        if ((length % 2) == 1) {
            cout << word.substr(length / 2, 1);
        } else {
            cout << word.substr((length / 2) - 1, 2);
        }
    }
}

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM