我正在编写代码以检查句子是否是回文。我觉得我的逻辑是正确的,但是用于检查字符串反向的if语句似乎不起作用。我已经在网上尝试了许多解决方案,但仍然一无所获。每个字符串都不是回文。我觉得错误在于(句子==反向):
#include <iostream>
#include <string>
#include <vector>
#include <fstream>
#include <sstream>
using namespace std;
int main(int argc, char *argv[]) {
while (true) {
string sentence;
string reverse = "";
cout << "Enter a sentence below to check (-1 to end):" << endl;
getline(cin, sentence);
if (sentence == "q") {
break;
}
for (int i = sentence.length(); i >= 0; i-- ) {
reverse += sentence[i];
}
cout << sentence << " reversed is: " << "[" << reverse << "]" << endl;
if (sentence == reverse) {
cout << sentence << " is a palindrome" << endl;
} else {
cout << sentence << " is not a palindrome" << endl;
}
cout << endl;
}
}
任何帮助将不胜感激。
答案 0 :(得分:5)
问题不是Sub RemoveSmallValues()
Dim myfilename As String
Dim myfilepath As String
Dim newfilename As String
Dim N As Long
Dim i As Long
Dim cellvalue As Long
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'The above is just standard lines that I normally put into my code, enchances the speed of the macro.
myfilepath = "C:\Snapshot.csv"
myfilename = "Snapshot.csv"
Workbooks.Open (myfilepath)
Workbooks(myfilename).Activate 'Makes SnapShot.csv the active workbook
N = Range("C1", Range("C1").End(xlDown)).Rows.Count
'counts the number of rows untill cell is BLANK, based on your code I used Column C.
'If your columns have headers then you will need to make this C2. Otherwise your headers will be included and will create a datatype error on CELLVALUE
For i = 1 To N 'Again if your columns have hearders, then i will need to be i = 2
cellvalue = Cells(i, 2).Value
If cellvalue <= 10000 Then Cells(i, 2).ClearContents
Next i
newfilename = "C:\SnapshotBB" 'new file path and file name without extension.
Workbooks(myfilename).SaveAs newfilename, FileFormat:=xlCSV 'Save the file with extension CSV
ActiveWorkbook.Close False 'Close the workbook without saving, as you have already saved the workbook with line before.
End Sub
。这就是这个部分:
if
for (int i = sentence.length(); i >= 0; i--) {
reverse += sentence[i];
}
是错误的,您必须从i = sentence.length()
开始。否则,它似乎在字符串中添加了空格字符,从而导致错误的结果。该循环应为:
i = sentence.length()-1
请注意,根据to the documentation:
返回对指定位置pos处字符的引用。没有 边界检查已执行。如果pos> size(),则行为为 未定义。
因此,不能保证添加的空格,任何事情都会发生。为了获得更安全的版本,请查看at函数,如果该位置无效,则此函数将引发异常,而不是默默地引起未定义的行为。
答案 1 :(得分:0)
字符串的结尾是length - 1
,请改用它:
for (int i = sentence.length() - 1; i >= 0; --i)
答案 2 :(得分:0)
为此替换for循环
for (int i = sentence.length()-1; i >= 0; i-- ) {