Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 获取字符串的中间字符。中间长度为偶数的两个字符_C++_String - Fatal编程技术网

C++ 获取字符串的中间字符。中间长度为偶数的两个字符

C++ 获取字符串的中间字符。中间长度为偶数的两个字符,c++,string,C++,String,编写一个函数,如果str的长度为奇数,则返回包含str中中间字符的字符串;如果长度为偶数,则返回两个中间字符的字符串。例如,middlemiddle返回dd 代码是这样编写的: #include <iostream> #include <string.h> using namespace std; int main() { string word; int length; cout << "Enter string: "; ci

编写一个函数,如果str的长度为奇数,则返回包含str中中间字符的字符串;如果长度为偶数,则返回两个中间字符的字符串。例如,middlemiddle返回dd

代码是这样编写的:

#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);
 }
}
我运行了它,问题是当使用字符串middle进行测试时,它将返回dle而不是dd.word.substrlength/2,length/2+1;这部分似乎是正确的,但为什么它会输出这样的答案?

您使用的方法不正确

当使用1个参数调用substr时,它将使用一个起始索引,并将返回字符串末尾的所有剩余字符。在这种情况下,这不是你想要的。您需要指定要返回的字符数,对于奇数长度的字符串,它是1

当使用2个参数调用substr时,它需要一个起始索引和一个字符计数,而不是您编码的索引范围。对于偶数长度的字符串,指定的索引和计数都是错误的。您需要从索引中减去1,并将字符数指定为2

请尝试类似以下内容:

包括 包括 使用名称空间std; int main{ 字符串字; 单词{ 字符串::size\u type length=word.length; 如果长度%2==1{
如果没有以下条件,就不能替代@Remy的答案:

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

对于初学者,必须包含声明标准类std::string的标头。必须删除标头

对于元素数为偶数的字符串,字符串中间部分的计算不正确。要从字符串中提取的元素数的计算也存在相同的问题,与字符串中的元素数无关

例如,程序可以通过以下方式查看示例

#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;
}

请注意,用户可能会中断输入。在这种情况下,您将有一个空字符串。这样的字符串应该正确处理。

substr的第二个参数是长度,所以只需使用2。是:是的。substr希望在新字符串中输入字符数。您需要两个字符。使用值2。需要一个字符时除外ER。然后使用1。顺便说一下,在C++中,使用STD::string,您不应该包含字符串。h,它是用于C样式函数的。参见。
Enter string: a
a

Enter string: ab
ab

Enter string: abc
b

Enter string: abcd
bc

Enter string: middle
dd