c++ - 在字符串中移动一个单词,单词之间用空格作为分隔符

标签 c++ c string

让我用一个例子更详细地解释我的问题。

给定一个字符串:

"Assonance is the reiteration of the same vowel sound at the beginning of several consecutive words"

如果我们想把第四个词,也就是reiteration,移到第二个词的位置,字符串会变成:

"Assonance reiteration is the of the same vowel sound at the beginning of several consecutive words"

给定一个 C 函数原型(prototype)如下:

void move(char *s, int word_begin_ind, int word_end_ind, int target_begin_ind)

如何实现这个功能来完成工作?

在上面的例子中,word_begin_ind = 17, word_end_ind = 27, target_begin_ind = 10

这不是作业。其实是一道面试题。我有一个算法。基本思想是这样的:

(1) 使用word_begin_indword_end_ind 复制目标词。

(2) 从target_begin_indword_begin_ind - 1,将每个字符移动到正确的位置。例如,将 word_begin_ind-1 移动到 'word_end_ind',将 word_begin_ind-2 移动到 'word_end_ind-1' 等等。

(3) 最后将拷贝移动到合适的位置(从target_begin_ind开始)。

希望大家能明白我在问什么。

您不需要使用 c 来完成这项工作。也欢迎使用 C++。

谁能帮我找到其他解决方案?

最佳答案

  1. 在一个位置的开始和另一个位置的结束之间取一个范围:

    "Assonance [is the reiteration] of the same vowel sound at the beginning of several consecutive words"
    
  2. 反转这个范围:

    "Assonance [noitaretier eht si] of the same vowel sound at the beginning of several consecutive words"
    
  3. 将此范围拆分为单词和其他所有内容:

    "Assonance [noitaretier|eht si] of the same vowel sound at the beginning of several consecutive words"
    
  4. 反向词:

    "Assonance [reiteration|eht si] of the same vowel sound at the beginning of several consecutive words"
    
  5. 颠倒一切-其他:

    "Assonance [reiteration|is the] of the same vowel sound at the beginning of several consecutive words"
    
  6. 那么你已经完成了。

关于c++ - 在字符串中移动一个单词,单词之间用空格作为分隔符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15212749/

相关文章:

python - 返回空字符串而不是 IndexError

c++ - 在 C++ 中寻找 Reactor 模式示例源代码

c++ - 使用 python 正则表达式从 C++ 源中提取命名空间

c - 如何终止嵌套循环

我可以在单独的函数中安装信号处理程序吗

java - 正则表达式将引用与最小字数匹配

c++ - 用于 C++ 游戏的通用 FSM?

c++ - 写入时 WaitForMultipleObjects 访问冲突

c - 我可以在C程序中ping吗?

c++ - 在 C++ 中使用 getline 忽略空格