我正在尝试使此函数返回没有数字,空格或其他字符,并且我应该使用.erase函数。我知道我的循环不断超出范围,但是我不知道如何解决它,并且我已经坚持了一段时间。如果用户键入“ dogs非常有趣”,而我需要该函数返回并输出“ dogsarealotoffun”,则感谢您的帮助。
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
//function to output string without spaces, numbers, or punctuations
string alphabetOnly (string input){
int size;
int i= 0;
size = (int)input.size();
while (input[i] < size){
if (isalpha(input[i])){
i++;
}
else
input.erase(input[i]);
}
return input;
}
int main() {
string input;
cout << "Enter a string to test: ";
getline(cin, input);
cout << "alphabetOnly: " << alphabetOnly(input) << endl;
}
答案 0 :(得分:1)
已编辑:我以前的回答太草率了(因为我正在学习,我需要从经过测试的代码讲话,而不是费尽心思)并且需要进行调试。问题在于,在其他情况下,您需要擦除字符,而不要递增i,因为字符串的长度刚刚更改,而且由于字符串的长度已更改,因此您需要将大小重置为新的长度。对不起,我们早点回答了,我当时没有实际使用编译后的代码。
#include <iostream>
#include <cctype>
#include <string>
//function to output string without spaces, numbers, or punctuations
std::string alphabetOnly (std::string input){
int size;
int i= 0;
size = (int)input.size();
while (i < size){
if (isalpha(input[i])){
i++;
}
else{
input.erase(i,1);
//do not increment i here since the index changed becauase of erase
size = (int)input.size();
}
}
return input;
}
int main() {
std::string input;
std::cout << "Enter a string to test: ";
std::getline(std::cin, input);
std::cout << input;
std::cout << "alphabetOnly: " << alphabetOnly(input) << std::endl;
return 0;
}
答案 1 :(得分:0)
类似这样的东西:
public boolean changeDocumnetMimeType(String documentId, String docMimeType) throws IOException {
com.filenet.wcm.api.TransportInputStream in1 = null;
com.filenet.wcm.api.ObjectStore docObjectStore;
com.filenet.wcm.api.Session session;
try {
session = ObjectFactory.getSession(this.applicationId, null, this.user,this.password);
session.setRemoteServerUrl(this.remoteServerUrl);
session.setRemoteServerUploadUrl(this.remoteServerUploadUrl);
session.setRemoteServerDownloadUrl(this.remoteServerDownloadUrl);
docObjectStore = ObjectFactory.getObjectStore(this.objectStoreName, session);
Document doc = (Document) docObjectStore.getObject(BaseObject.TYPE_DOCUMENT, documentId);
in1 = doc.getContent();
System.out.println("documnet MIME type is : " + in1.getMimeType());
//how to Update mimeType for the document???
} catch (Exception ex) {
ex.printStackTrace();
}
if (in1 != null) {
in1.close();
}
return true;
}
答案 2 :(得分:0)
您的代码有很多错误,但是首先要纠正您的主要错误。
#include <iostream>
#include <cctype>
#include <cstring>
using namespace std;
//function to output string without spaces, numbers, or punctuations
string alphabetOnly (string input){
int size;
int i= 0;
size = (int)input.size();
while (i < size){
if(isalpha(input[i]))
{
i++;
}
else
input.erase(input.begin( ) + i );
}
return input;
}
int main() {
string input;
cout << "Enter a string to test: ";
getline(cin, input);
cout << "alphabetOnly: " << alphabetOnly(input) << endl;
}
但这是非常低效的,因为您每次删除时都会将所有其余未选中的字符回缩。
您应该使用类似
input.erase( remove_if( input.begin(), input.end(), not( isalpha ) ), input.end( ));
这被称为删除惯用语,您可以在任何地方查找。