我想将a转换std::string为小写.我知道这个函数tolower(),但是在过去我遇到了这个函数的问题,并且它很难理想,因为使用a std::string会需要迭代每个字符.
有没有一种方法可以100%的时间运作?
通常在迭代字符串(或任何可枚举对象)时,我们不仅对当前值感兴趣,还对位置(索引)感兴趣.要通过使用string::iterator我们必须维护一个单独的索引来实现这一点:
string str ("Test string");
string::iterator it;
int index = 0;
for ( it = str.begin() ; it < str.end(); it++ ,index++)
{
cout << index << *it;
}
Run Code Online (Sandbox Code Playgroud)
上面显示的样式似乎不比'c-style'优越:
string str ("Test string");
for ( int i = 0 ; i < str.length(); i++)
{
cout << i << str[i] ;
}
Run Code Online (Sandbox Code Playgroud)
在Ruby中,我们可以以优雅的方式获取内容和索引:
"hello".split("").each_with_index {|c, i| puts "#{i} , #{c}" }
Run Code Online (Sandbox Code Playgroud)
那么,C++中迭代可枚举对象并跟踪当前索引的最佳实践是什么?
我尝试通过char迭代字符串char.我试过这样的事情:
void print(const string& infix)
{
char &exp = infix.c_str();
while(&exp!='\0')
{
cout<< &exp++ << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
所以这个函数调用print("hello"); 应该返回:
h
e
l
l
o
Run Code Online (Sandbox Code Playgroud)
我尝试使用我的代码,但它根本不起作用.顺便说一句,参数是引用而不是指针.谢谢
我试图从c ++中的输入字符串中删除所有非字母字符,但不知道如何操作.我知道它可能涉及ascii数字,因为这是我们正在学习的内容.我无法弄清楚如何删除它们.我们只学习了循环,还没有启动数组.不知道该怎么办.
如果字符串是Hello 1234 World&*
它将打印HelloWorld
假设我有字符串
string str = "this is a string";
和一个十六进制值
int value = 0xbb;
我将如何在 C++ 中对字符串与十六进制值执行按字节异或?
如何逐字符扫描字符串并在单独的行中打印每个字符,我正在考虑将字符串存储在数组中,并使用for循环进行打印,但是我不知道如何...。 !!!
这是我的代码:
#include "stdafx.h"
#include<iostream>
#include<string>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
string str;
char option;
cout << "Do you want to enter a string? \n";
cout << " Enter 'y' to enter string or 'n' to exit \n\n";
cin >> option ;
while ( option != 'n' & option != 'y')
{
cout << "Invalid option chosen, please enter a valid y or n \n";
cin >> option;
}
if (option == 'n')
return 1; …Run Code Online (Sandbox Code Playgroud) 考虑一个arr[10]大小为10 的数组.在获取/显示数据时,我们使用以下常见语法的for循环
for(int i=0;i<10;i++)
Run Code Online (Sandbox Code Playgroud)
如果是字符串,就像
for(int i=0;strlen(arr)>i;i++)
Run Code Online (Sandbox Code Playgroud)
但我在某处读过一个更简单的表达式,arr[i]可以只用在条件的位置.我已经尝试运行具有该条件的代码.但是我收到了一个错误.那么有一个类似的,简单的条件表达式可以用于数组/字符串吗?