如何替换字符串中的字符?
string title = "I like to code."
char arr[title.size() + 1];
strcpy(arr, title.c_str());
int i = 0;
while(arr[1][i] != 0){
if(arr[1][i] == ' '){
arr[1][i] = '-';
};
i++;
};
string name(arr);
return name;
这是我的代码已经捣碎了。正如您所看到的,我正在将一个字符串转换为一个数组,通过char遍历数组char,在我继续使用破折号替换空格,然后将最终结果转换回字符串。问题是编译器会为'while'语句抛出'错误:数组下标的无效类型'以及它后面的两行。我怎样才能解决这个问题?谢谢,全部!
我尝试了什么:
我有尝试使用 #include< algorithm>
中的 std :: replace
模板,但无济于事。
This is the code that I have mashed together. As you can see, I am converting a string into an array, going through the array char by char, replacing spaces with dashes as I go along, then converting the end result back into a string. The problem is that the compiler throws back 'error: invalid types for array subscript' for the 'while' statement and the two lines after it. How can I fix this? Thanks, all!
What I have tried:
I have tried using the std::replace
template from #include <algorithm>
, but to no avail.
尝试用arr [i] arr [1] [i]
/ code>让编译器开心。
跟踪其他错误:
你应该学会尽快使用调试器尽可能。而不是猜测你的代码在做什么,现在是时候看到你的代码执行并确保它完成你期望的。
调试器允许你跟踪执行逐行检查变量,你会看到它有一个停止做你期望的点。
调试器 - 维基百科,免费的百科全书 [ ^ ]
掌握Visual Studio 2010中的调试 - A初学者指南 [ ^ ]
调试器在这里向您展示您的代码正在做什么,您的任务是与它应该做什么进行比较。 />
当代码不做ex的时候你已经接近了一个错误。
Try to replace allarr[1][i]
witharr[i]
to make the compiler happy.
To track other bugs:
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.
The debugger allow you to follow the execution line by line, inspect variables and you will see that there is a point where it stop doing what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
When the code don't do what is expected, you are close to a bug.