1

输入我的符号后,我想打印一个子词。比如像这样。

我要输入abcdefghijk d

并得到efghijk

这是我的无条件代码体。

   #include <iostream>

   int main(){
   const int n = 21;
   char word[n];
   std::cin>>word;
   char symbol;
   std::cin>>symbol;
   int i = 0;
   char*p = word;
   while(word[i]!='\0' && word[i]!=symbol){
   // what condition I need to write here?
   i++;
   std::cout << p <<std::endl;
  }

  return 0;
  }

感谢您的帮助))

4

2 回答 2

0

你可以尝试这样的事情:

int main()
{
    std::string text;
    std::cout << "Enter sentence: ";
    std::getline(std::cin, text);
    char  split_char;  
    std::cout << "Enter subword / split character: ";
    std::cin >> split_char;

    std::string::size_type split_position = text.find(split_char);
    std::string::size_type word_end_position = text.find_first_of(" \t", split_position);
    if (word_end_position == std::string::npos)
    {
        word_end_position = text.length();
    }
    std::string split_text = text.substr(split_position, word_end_position, split_position);
    std::cout << split_text << "\n";

    return 0;
}
于 2021-01-30T20:05:40.657 回答
0

在不满足拆分字符的情况下,您需要将指针 p 向右移动。

char*p = word;
while(word[i]!='\0' && word[i]!=symbol){
    p++;
    i++;
}
p++;
std::cout << p << std::endl;

在第一行,您的指针 p 指向单词的开头(即在第一个字符上)。然后 while 循环测试每个字符,直到我们找到拆分字符。每次一个字符不匹配你拆分字符,你增加 p 并使其指向下一个字符。

但是,您需要在循环后最后一次增加它以指向拆分字符之后。

请注意,更短的方法是:

char*p = word;
while(word[i]!='\0' && word[i]!=symbol){
    i++;
}
p = p + i + 1;
std::cout << p << std::endl;
于 2021-01-30T20:01:53.700 回答