在C中动态分配字符串

时间:2014-11-10 03:10:06

标签: c++ c string

我在UVa's online judge中执行一个相对简单的字符串问题来练习字符串,因为我在C中遇到了很多困难。问题基本上要求检查字符串B是否包含另一个字符串答:如果你删除了杂乱的'并连接剩余的字符,例如"ABC"中包含"AjdhfmajBsjhfhC",在这种情况下是真的。

所以,我的问题是如何有效地为字符串分配内存,而我不知道它的长度?我所做的是使字符串非常大char Mstring[100000],从输入读取,然后使用strlen(Mstring)将字符串复制到正确大小的char数组。类似的东西:

char Mstring[100000];

scanf("%s",Mstring);
int length = strlen(Mstring);
char input[length+1]={0};
for(int i = 0; i<length;i++){
    input[i]=Mstring[i];
}

在C中有更好/标准的方法吗?我知道C对字符串没有很好的支持,如果没有更好的方法在C中做这个可能在C ++中?

1 个答案:

答案 0 :(得分:1)

如果您可以选择使用C ++(如您所述),那将使您的生活更轻松。然后,您可以使用STL字符串(std :: string)来管理动态大小的字符串。您也可以删除旧的scanf()野兽并使用std :: cin。

示例:

#include <iostream>
#include <string>

void main()
{
    std::string sInput;
    std::getline(std::cin, sInput);

    // alternatively, you could execute this line instead:
    // std::cin >> sInput;
    // but that will tokenize input based on whitespace, so you
    // will only get one word at a time rather than an entire line
}

描述如何管理可以在C中动态增长的字符串将需要更多的解释和关注,听起来你真的不需要它。如果是这样,那么这是一个起点:http://www.strchr.com/dynamic_arrays