【问题标题】:BinarySearch - Replace a string element with another string element once foundBinarySearch - 找到后用另一个字符串元素替换一个字符串元素
【发布时间】:2011-09-22 13:42:22
【问题描述】:

如何使二进制搜索将字符串数组的元素替换为字符串数组的另一个元素?这是我程序的最后一部分,我不明白...我知道你使用 char 的 strcpy 或 .replace 等。

我有一个结构,它有一个“orginalWord”和一个“replacementWord”,然后是一个“inputword”的字符串数组,它接受 inputword,在结构数组中找到它(与 orginalWord 相比),然后一次找到(它确实找到了它......该部分有效,它找到了正确的元素编号,所以我知道搜索是正确的)用“replacementword”替换“inputword”。我只是不能让它用它找到的“reaplcementWord”替换“inputword”中的元素。请帮忙!!为了便于阅读,我将把 Binarysearch 函数与我的其余代码分开发布。我知道这应该很简单,但我这辈子都记不起来了。

示例:所以...searchitem 是 inputword[20] = "Like"。结构数组...加密[50].OrginalWord = "喜欢"。找到匹配...加密[50].ReplacementWord = "Ducks"。我想将“鸭子”放入 inputword[20]。我将如何使用 BinarySearch 来做到这一点?

//Function call within main:
for(number=0; number < plaincount; number++)
        { BinarySearch(encryption, count, inputword[number]);
         } 

int BinarySearch (StringPair correctword[], int size, string searchitem)
{   
    int middle =0, start = 0, last = size-1;
    bool found = false;
    int position = -1;
    while (!found && start <= last)
    { 
        middle = (start + last)/2; // Midpoint // Was a breakpoint here, why?
        if(correctword[middle].orginalWord == searchitem)
        {               
            position = middle;
            cout << "Replacing word: " << searchitem << " With: " << position << endl;

            searchitem.swap(correctword[position].replacementWord);

            found = true;
            return position; // Return new value for inputword array?
        }
        else if (correctword[middle].orginalWord < searchitem)
            { start = middle+1; }
        else last = middle-1;
    }
    cout << "Misspelled word found: " << searchitem << endl;
    return false;
}

【问题讨论】:

  • 您是否尝试在调用者中修改 searchitem?
  • @VaughnCato 是吗?一旦找到匹配的单词,我希望它替换字符串数组中用作搜索项的元素。使用它找到匹配项的字符串。希望这是有道理的。
  • 我有一个包含 2 个字符串的结构数组,“OriginalWord”和“ReplacementWord”。其中有 86 个。然后我有一个大约 200 的字符串数组“inputword”。我使用“inputword”作为搜索项,在结构数组中搜索,与它确实找到的“OriginalWord”进行比较。但是一旦找到它,我希望它在该数组中获取该元素编号,并使用“ReplacementWord”并放置该新字符串,其中“intputword”的字符串数组中的元素被用作搜索项。
  • 所以...searchitem 是 inputword[20] = "Like"。结构数组...加密[50].OrginalWord = "喜欢"。找到匹配...加密[50].ReplacementWord = "Ducks"。我想将“Ducks”放入 inputword[20]。

标签: arrays string struct binary-search


【解决方案1】:

如果要修改searchitem,需要通过引用传递:

int BinarySearch (StringPair correctword[], int size, string &searchitem)

【讨论】:

  • 做到了!谢谢!!它现在正在替换单词!看来我一定是在其他地方出错了,因为只有 80% 的单词被替换,但它有效!谢谢! :)
猜你喜欢
  • 2019-12-18
  • 2011-04-07
  • 2015-01-10
  • 1970-01-01
  • 1970-01-01
  • 2021-09-26
  • 2023-03-14
  • 1970-01-01
  • 2013-12-03
相关资源
最近更新 更多