检查字符串末端的字符
checking for a character on the end of a string
im试图检查字符串末端的下划线,我有此代码,但我仍然没有成功。它仅检查字符串开头的下划线。正如我评论的那样,检查最后一个字符不在这里...我不知道如何在..
中编码它。void Convert(string input){
string output = "";
string flag = "";
bool underscore = false;
bool uppercase = false;
if ( islower(input[0]) == false){
cout << "Error!" <<endl;
return;
}
for (int i=0; i < input.size(); i++){
if ( (isalpha( input[i] ) || (input[i]) == '_') == false){
cout << "Error!" <<endl;
return;
}
if (islower(input[i])){
if (underscore){
underscore = false;
output += toupper(input[i]);
}
else
output += input[i];
}
else if (isupper(input[i])){
if (flag == "C" || uppercase){
cout << "Error!"<<endl;
return;
}
flag = "Java";
output += '_';
output += tolower(input[i]);
}
else if (input[i] == '_'){
if (flag == "Java" || underscore){
cout << "Error!" <<endl;
return;
}
flag = "C";
underscore = true;
}
}
cout << output <<endl
;
}
在字符串/>
的末尾编辑/寻找下划线for (int i=input.size()-1; i >=0; i--){
if ( input[i]=='_' ){
cout<<"Chyba"<<endl;
break;
}
}
如果您要做的就是检查字符串的最后一个元素是否是下划线,则
if (!input.empty())
return *(input.rbegin()) == '_';
或
if (!input.empty())
return input[input.size()-1] == '_';
或在C 11中使用Back
if (!input.empty())
return input.back() == '_';
您的逻辑看起来有点奇怪,这可能使它很难理解。让我们重新排列并删除一些括号:
if ( (isalpha( input[i] ) || (input[i]) == '_') == false){
if ( (isalpha( input[i] ) || input[i] == '_' ) == false){
if ( !(isalpha(input[i]) || input[i] == '_') ){
if (! ( isalpha(input[i]) || input[i] == '_' ) ){
请注意,!
表示not
,这使得false语句正确。这与您的==false
一样,但以(可以说是清晰的方式)。
所以您的意思是:
If this character is an Alpha or an Underscore, don't continue.
但是您要问的是:
Is there an underscore at the end of the string?
由于您对字符串的末尾感兴趣,为什么不逆转您的前面?
for (int i=input.size()-1; i >=0; i--){
请注意,由于C 中的数组是基于0的数组,因此字符串的长度大于其末端1,因此我们从input.size()-1
字符开始。
那么,为什么我们不忽略空白空间,如果看到下划线?
for (int i=input.size()-1; i >=0; i--){
if( input[i]==' ' || input[i]=='t' )
continue;
else if ( isalpha(input[i]) ){
cout<<"String ends with an alpha."<<endl;
break;
} else if ( input[i]=='_' ){
cout<<"String ends with an underscore."<<endl;
break;
}
}
请注意,else if
和continue
和break
的使用使您可以轻松地遵循此处发生的事情。
相关文章:
- 从 argv[1] 转换为字符 * 字符串后有什么问题?
- 将 NULL 与 C 的字符* 字符串一起使用
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法将常量字符字符串传递给模板类
- 如何组合一个宽字符字符串,中间插入一些空字符
- 如何将二维数组类型字符(字符串)作为函数参数传递?
- 从给定索引返回子字符字符串的函数
- 字符 [](c 字符串)的初始化标准
- 如何将字符字符串用作数学运算符
- 将 Unicode 字符/字符串写入文件
- C++,字符* 字符串修改
- 如何有效地用不同的整数元素替换字符字符串的元素
- C++:如果我们在字符串中添加一些整数,为什么它会从开头删除该数量的字符?(字符串 + 整数)
- strcpy正在复制sth字符i字符串.如何解决此错误
- 在C++中将双精度转换为字符*/字符串
- C 中的宽字符字符串
- 如何提取C 中的字符/字符串之间的字符串
- 无法将字符/字符串转换为int
- 带有指针的反转字符字符串
- 反转字符串中的 n 个字符(字符串中没有空格),而不使用 c++ 中的内置函数