复制
收藏
提问
简洁
#include <iostream> using namespace std; void main( ) { char ch[7] = { "12ab56" }; int i, s = 0; for (i = 0; ch[i] >= 'a' && ch[i] <= 'z'; i+=2) cout << i << endl;}执行结果是什么?为什么?
4月前
全网
文档
学术
百科
知识库
回答简洁模式
深入研究一些
在C++程序中,遍历字符数组并输出每个字符及其索引可以通过多种方式实现。以下是一些常见的方法:
方法一:使用数组和下标
这是最直接的方法,通过数组的下标来访问每个元素,并使用strlen
函数来确定数组的长度。需要包含cstring
库来使用strlen
函数。
#include <iostream>
#include <cstring>
int main() {
char str[] = {'z', 'i', 'f', 'u', 's', 'h', 'u', 'z', 'u'};
for (int i = 0; i < strlen(str); i++) {
std::cout << "Index " << i << ": " << str[i] << std::endl;
}
return 0;
}
方法二:使用指针和while
循环
利用字符数组以'\0'
(空字符)结束的特性,可以使用指针来遍历数组,直到遇到空字符。
#include <iostream>
int main() {
char str[] = {'z', 'i', 'f', 'u', 's', 'h', 'u', 'z', 'u', '\0'};
char *p = str;
int index = 0;
while (*p != '\0') {
std::cout << "Index " << index << ": " << *p << std::endl;
p++;
index++;
}
return 0;
}
方法三:使用std::distance
和std::find
这种方法适用于更复杂的场景,比如需要找到特定元素的索引。这里使用std::distance
来计算从数组开始到找到的元素之间的距离。
#include <iostream>
#include <algorithm>
int main() {
char str[] = {'z', 'i', 'f', 'u', 's', 'h', 'u', 'z', 'u'};
char target = 'f';
int index = std::distance(str, std::find(str, str + 9, target));
std::cout << "Index of '" << target << "': " << index << std::endl;
return 0;
}
方法四:使用基于范围的循环(C++11及以上版本)
C++11引入了基于范围的循环,这使得遍历数组变得更加简洁。
#include <iostream>
#include <string>
int main() {
char str[] = {'z', 'i', 'f', 'u', 's', 'h', 'u', 'z', 'u'};
for (size_t i = 0; str[i] != '\0'; ++i) {
std::cout << "Index " << i << ": " << str[i] << std::endl;
}
return 0;
}
方法五:使用std::string
类的成员函数
如果字符数组实际上是一个字符串,可以使用std::string
类的成员函数来获取长度和遍历。
#include <iostream>
#include <string>
int main() {
std::string str = "zifuushuzu";
for (size_t i = 0; i < str.length(); ++i) {
std::cout << "Index " << i << ": " << str[i] << std::endl;
}
return 0;
}
在上述方法中,我们可以看到如何通过不同的方式遍历字符数组并输出索引和对应的字符。每种方法都有其适用的场景和优势。1235678
你觉得结果怎么样?