![](/img/trans.png)
[英]How can i get sentence instead of word? i want to search second string in first string by strstr in c++
[英]How can I reach the second word in a string?
我是新來的,這是我的第一個問題,所以不要太苛刻:]
我正在嘗試反轉一個句子,即每個單詞都分開。 問題是我無法到達第二個單詞,甚至無法到達一個1單詞句子的結尾。 怎么了?
char* reverse(char* string)
{
int i = 0;
char str[80];
while (*string)
str[i++] = *string++;
str[i] = '\0'; //null char in the end
char temp;
int wStart = 0, wEnd = 0, ending = 0; //wordStart, wordEnd, sentence ending
while (str[ending]) /*@@@@This part just won't stop@@@@*/
{
//skip spaces
while (str[wStart] == ' ')
wStart++; //wStart - word start
//for each word
wEnd = wStart;
while (str[wEnd] != ' ' && str[wEnd])
wEnd++; //wEnd - word ending
ending = wEnd; //for sentence ending
for (int k = 0; k < (wStart + wEnd) / 2; k++) //reverse
{
temp = str[wStart];
str[wStart++] = str[wEnd];
str[wEnd--] = temp;
}
}
return str;
}
您的代碼對於C ++來說有點單調,因為它實際上並未使用許多常見且便捷的C ++工具。 就您而言,您可以從中受益
std::string
負責維護足夠大的緩沖區以容納您的字符串數據。 std::istringstream
可以輕松為您將字符串拆分為空格。 std::reverse
可以反轉一系列項目。 這是使用這些功能的替代版本:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>
std::string reverse( const std::string &s )
{
// Split the string on spaces by iterating over the stream
// elements and inserting them into the 'words' vector'.
std::vector<std::string> words;
std::istringstream stream( s );
std::copy(
std::istream_iterator<std::string>( stream ),
std::istream_iterator<std::string>(),
std::back_inserter( words )
);
// Reverse the words in the vector.
std::reverse( words.begin(), words.end() );
// Join the words again (inserting one space between two words)
std::ostringstream result;
std::copy(
words.begin(),
words.end(),
std::ostream_iterator<std::string>( result, " " )
);
return result.str();
}
在第一個單詞的末尾,經過遍歷后,str [wEnd]是一個空格,當您分配end = wEnd時,您會記住該索引。 立即,您反轉單詞中的字符。 那時,str [ending]不是空格,因為您在單詞的字母反轉中包括了該空格。
根據其余輸入中的單詞之間是否有多余的空格,執行從這一點開始有所不同,但是它最終會隨着您反轉以字符串的空終止符結尾的單詞而結束,因為您結束了遞增wEnd的循環空終止符,並將其包括在最終單詞反轉中。
接下來的迭代從輸入字符串的初始化部分開始,執行未確定,因為,黑克,誰知道該數組中的內容(str是堆棧分配的,因此它位於堆棧所占用的內存中的任何內容在那時候)。
最重要的是,除了在反向循環中,您不會更新wStart,而且它永遠不會一直移動到wEnd(請參閱循環退出條件),因此請考慮一下,您將永遠不會超越第一個字。 假設該問題已解決,那么您仍然會遇到我最初概述的問題。
所有這些都假定您不只是向該函數發送了超過80個字符的東西,並且以這種方式破壞了它。
哦,正如在對該問題的評論之一中提到的那樣,您將返回堆棧分配的本地存儲,該存儲也不會出現任何問題。
哦,男孩。 從哪兒開始?
如果可以,在C ++中使用std::string
代替char*
。
如果用戶輸入string
則char[80]
有溢出風險; 應該動態分配。 最好使用std::string
; 否則使用new
/ new[]
。 如果您打算使用C,則使用malloc
。
cmbasnett還指出,如果按照您的方式聲明/分配str
,則實際上無法返回str
(並獲得預期的結果)。 傳統上,您將傳遞char* destination
而根本不分配任何功能。
將
ending
設置為
wEnd + 1
;
不管那個,我誤讀了while循環。 wEnd
指向所討論字符串的最后一個非空字符(最終,如果工作正常),因此為了使
str[ending]
脫離循環,您必須遞增一次以獲取空字符。
看來您需要使用((wEnd - wStart) + 1)
,而不是(wStart + wEnd)
。 盡管在這種情況下,您實際上應該使用while(wEnd > wStart)
代替for
循環。
您還應該設置wStart = ending;
或在退出循環之前執行的操作,否則將卡在第一個單詞上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.