2017-04-02 32 views
-2
#include "stdafx.h" 
#include <iostream> 
#include <fstream> 
#include <string> 
#include <iomanip> 
using namespace std; 

int main() 
{ 
    string sentence = "some random sentence"; 
    int i = 0; //runs through the bigger string 
    int j = 0; //runs through the smaller string 
    int k = 0; //variable to mark the position where the string starts being equal in order to delete it using substring 
    string remove = "random"; 
    int a = sentence.size(); 
    int b = remove.size(); 
    while (i < a) 
    { 
     if (sentence[i] == remove[j]) 
     { 
      if (b == j - 1) 
      { 
       cout << sentence.substr(0, k) << sentence.substr(i, (a - 1)); 
       break; 
      } 
      else 
      { 
       i++; 
       j++; 
      } 
     } 
     else 
     { 
      i++; 
      j = 0; 
      k++; 

     } 

    } 
     return 1; 
} 

我想從較大的字符串中移除隨機字並將其打印出來,但是當我運行代碼時,它不返回任何內容。少了什麼東西? 我已經嘗試了在de「cout」之下放置一個突破,但它不起作用。使用C++早先使用cout取出while循環

謝謝:)

+0

您無法使用句子[i]訪問單詞,該句子只會在第i個位置提供單個字符 – alDiablo

+0

句子[i]將字符逐個字符進行比較,並保存事物相等的初始位置,字完成。在那之前,我寫了一個子字符串,直到該字的第一個字母和另一個從該字的最後一個字母末尾開始的子字符串。 –

回答

0

由於b == 6Ĵ必須是7爲了b == J-1成爲事實。但刪除[6]是終止隨機串的\ 0,所以Ĵ永遠不能生長超出6.

+0

謝謝,我現在看到它。 ((b - 1)== j)而不是(b == j - 1) 這段代碼還有一些其他問題,但現在至少它返回了一些東西。感謝您的幫助:) –

0

下面是我編輯

if (b-1 == j) 
{ 
    cout << sentence.substr(0, k) << sentence.substr(i+2, (a - 1)); 
    break; 
} 

這是假設該代碼,單詞之間有空格。

+0

我只是想通了。感謝您的回覆和幫助:) –