2013-05-27 54 views
-3

我已經編寫了以下程序,它將刪除string1中存在於string2中的所有常用字符。C++:通過函數使用指針操縱字符串

#include<iostream> 
#include<string> 
#include<iterator> 

using namespace std; 

void DelCommonChar(char *input, string s2) 
    { 
      string s1(input); 
      string::iterator it1; 
      string::iterator it2; 

      for(it1=s1.begin();it1<s1.end();it1++) 
      { 
        for(it2=s2.begin();it2<s2.end();it2++) 
        { 
          if(*it1==*it2){it1=s1.erase(it1);it1--;} 
        } 
      } 
      cout<<s1<<endl;    // Line Number 20 
    } 


    int main() 
    { 
      char c[32]; 
      strncpy(c,"Life of Pie",32); 
      DelCommonChar(c,"def"); 
      cout<<c<<endl;    //Line Number 29 
    } 

Output:Li o pi ......... printed through line number 20. 

但現在我想chagne變量c[32]本身是在main function,我想line number 29打印輸出。

你能幫我嗎,如何改變變量c[32]只在函數DelCommonChar裏面?

注意:我不想更改函數返回數據類型void

+0

請不要用這樣的行號碼發佈代碼;它可以防止讀者將其粘貼到編輯器中並能夠編譯它。 –

+0

@OliCharlesworth我想通過查看行號來簡化讀者,因爲我已經提到了問題中的行號。使用記事本++來垂直選擇列和刪除可以提供幫助。 – CodeCodeCode

+0

@CodeCodeCode:我很確定讀者不需要行號。只是用評論或其他東西來標記興趣點。例如,在行結尾處出現「// <--- ---這是一個問題」。 – SigTerm

回答

1

如果您無法修改功能簽名。你可以使用「c_str()」來返回C字符串。這不被推薦。

#include<iostream> 
#include<string> 
#include<iterator> 

using namespace std; 

void DelCommonChar(char *input, string s2) 
{ 
     string s1(input); 
     string::iterator it1; 
     string::iterator it2; 

     for(it1=s1.begin();it1<s1.end();it1++) 
     { 
       for(it2=s2.begin();it2<s2.end();it2++) 
       { 
         if(*it1==*it2){it1=s1.erase(it1);it1--;} 
       } 
     } 
     std::strcpy (input, s1.c_str()); 
} 


int main() 
{ 
     char *c = (char *)malloc(32); 
     strncpy(c,"Life of Pie",32); 
     DelCommonChar(c,"def"); 
     cout<<c<<endl; 
} 
0

當初始化s1:中input

string s1(input); 

它的內容複製到其內部緩衝區。 Modfying s1不會更改原始緩衝區。如果您想要在輸入內存儲內容,請將其複製回來(strcpy,strncpy,memcpy-它們都是「不安全」的),或者直接在input上運行。

一個更好的主意是避免使用C字符串(char*)並使用帶引用的std :: strings。

void DelCommonChar(std::string &input, string s2) 
{ 
     std::string &s1 = input;//you don't need that, you can use input directly. 
     ... 

} 
+0

根據您的建議更改會引發錯誤。 void DelChar1(string&input,string s2) {...............}'Below Error:'it01.cpp:28:error:無效初始化類型的非常量引用'char *' it01.cpp:7:error:在'void DelChar1(std :: string&,std :: string)'的參數1中傳遞'std :: string&'這是因爲我我試圖將'char *'傳遞給'string'對象。哪個編譯器不接受。 – CodeCodeCode

+0

@CodeCodeCode:這意味着你必須擺脫'* char'並顯然使用'std :: string'而不是它作爲變量。 – SigTerm

0

您可以維護兩個指針,一個檢查,一個寫入。例如:

int check=0,write=0; 
while (input[check]) 
{ 
    if (input[check] is not to be deleted) 
    { 
     input[write++]=input[check]; 
    } 
    ++check; 
} 
input[write]=0; 
+0

你想提的。我不明白你的邏輯。 – CodeCodeCode

+0

這個代碼比你的方法更**效率更高,也更簡單。會發生什麼是我們只能將你的字符串「凝聚」到想要的字符。 – Szidor