[英]Invalid conversion from char to String* C++
String* substr(String* str, int start, int end)
{
String* substring = new String;
for(int i = start; i < end; i++)
{
substring = str->text[i];
}
return substring;
}
我需要將子字符串存儲在String結構的文本數組成員中。 該方法應該是數組的一部分(由定界符分隔),並將其存儲在變量str1和str2中,然后對其進行比較。 我在第6行中遇到問題,該行中的子字符串應該被創建和存儲。
由於沒有人回答...首先更改您的結構:
struct String {
char* text; // Removed const
int sz;
};
現在,改變你的功能
String* substr(String* str, int start, int end)
{
String* substring = new String;
//Alloc enough space to hold chars + EOS
substring->text = new char[end - start + 1];
// Save string length - does not include EOS
substring->sz = end - start;
for(int i = start; i < end; i++)
{
// TODO: Error checking should be added to make sure it doesn't go
// beyond original string bounds
// Copy the substring
substring->text[i - start] = str->text[i];
}
// Add end of string
substring->text[substring->sz] = '\0';
return substring;
}
注意,通過這種方式,您以后需要刪除數組和結構:
delete [] substring->text;
delete substring;
或者,您可以只使用std :: string ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.