2011-12-28 94 views
0
for each (std::string s in m_intro.text) // std::vector<string> 
    { 
     for (int i = 0; i < s.length(); i++) 
     { 
      char* chr = &s.at(i); 
      chr[i+1] = NULL; 
      std::string t(chr); 

      // other code is used below not shown as not relivent 

     } 

    } 

我想从字符串中获取字符。我得到的每个字符然后想变成一个字符串(有一个函数需要一个const std::string&从字符串获得单个字符串

上面的代码工作一次,但在第一个循环后,整个s为空。我可以看到为什么会发生这种情况。

我想要的是从每个循环中获取s的下一个字符并将其存储为字符串。

+2

你试图完成什么? – 2011-12-28 14:43:40

+2

这是C++的一种方式,可以让你在脚下自拍。 – 2011-12-28 14:44:05

+0

这看起来不像C++。 – 2011-12-28 14:45:37

回答

10
char* chr = &s.at(i); 
chr[i+1] = NULL; 
std::string t(chr); 

char是一个C-字符串(或char阵列)的一部分,则所使用的权利(如果过时)的下一个元素设置为NULL终止字符串的方法。

然而在这种情况下,这是不相关的;你只是索引到std::string并用NULL替换它的所有字符,这当然不是你的意思。

std::string有一个构造函数,你可以用它来避免这种龌龊:

std::string t(1, s.at(i)); 
// ^ ^^
// |  | | 
// string  | | 
//   | | 
//  of length 1 | 
//  char  | 
//     | 
//  each having value s.at(i) 

没有必要惹指针或char阵列或NULL -termination。

+0

**注意:** Francois的'.substring'方法也很好。 – 2011-12-28 16:23:01

1

您可以通过将赋值给循环中的元素来自行清除字符串。你不应该使用字符串的内部。相反,创建一个临时的一个字符的字符串,并在一个循环中重新分配它的第一个字符,像这样:

for each (std::string s in m_intro.text) // std::vector<string> 
    { 
     string tmp("_"); 
     for (int i = 0; i < s.length(); i++) 
     { 
      tmp[0] = s[i]; 

      // other code is used below not shown as not relivent 

     } 

    } 
0
char* chr = &s.at(i); 

这是一个错误。您编辑源字符串,使其元素\ 0(零终止),截断它。 试试这个代码:

 for (int i = 0; i < s.length(); i++) 
     { 
      char chrstr[2]; 
      chrstr[0] = s.at(i); 
      chrstr[1] = NULL; 
      std::string t(chrstr); 

      // other code is used below not shown as not relivent 
     } 
1

这是功课吗?为什么你认为“在第一个循环之后s整个为空”?这看起来很清楚,我看着代码,它表示不理解字符串如何在C/C++中工作...

这就是说,这里有一个可能的方法来实现你正在寻找的东西用于:

for each (std::string s in m_intro.text) // std::vector<string> 
    { 
     for (int i = 0; i < s.length(); i++) 
     { 
      std::string t = s.substring(i, 1); 

      // other code is used below not shown as not relevant 
     } 

    } 
+0

他很好地理解了这个问题。唉我不能downvote你,因为你的解决方案是好的:) – 2011-12-28 16:22:28

+0

@ TomalakGeret'kal:你太善良... – Francois 2011-12-29 05:31:43

+0

是的,我知道..:P – 2011-12-30 14:49:26