[英]Checking if the first character of all the strings are same or not in a array of strings
我有一个字符串数组,我想检查所有字符串的第一个字符是否相同。
我知道如何通过这种方法检索字符串的第一个字符
char first_letter;
first_letter = (*str)[0];
最初,我认为 go 是蛮力的方式,通过使用嵌套的 for 循环检查每个字符串的第一个字母。
int flag = 0
char f1,f2;
for(int i = 0;i < size_arr - 1;i++){
f1 = (*str[i])[0];
for(int j = i + 1;j < size_arr;j++){
f2 = (*str[j])[0];
if(f1 != f2)
flag += 1;
}
}
if(!(flag))
cout<<"All first characters same";
else
cout<<"Different";
但是我需要一种方法来查找数组中存在的所有字符串的第一个字母是否相同。 有什么有效的方法吗?
I made this C approach for you (it's because you have used character arrays here, not std::string
of C++ – so it's convenient to describe using C code):
#include <stdio.h>
#define MAX_LENGTH 128
int main(void) {
char string[][MAX_LENGTH] = {"This is string ONE.", "This one is TWO.",
"This is the third one."};
char first_letter = string[0][0];
int total_strs = sizeof(string) / sizeof(string[0]);
int FLAG = 1;
// Iterate through each letter of each string
for (int i = 0; i < total_strs; i++)
// First letter of the string is equal to first_letter?
if (string[i][0] != first_letter) {
FLAG = 0; // set to 0 as soon as it finds
break; // the initial_letter is NOT equal to the first
} // letter
if (FLAG)
fprintf(stdout, "The strings have the same initial letters.\n");
else
fprintf(stdout, "Not all strings have the same initial letters.\n");
return 0;
}
如果您想将其转换为 C++ 代码,没有什么大问题 - 只需将stdio.h
替换为iostream
,将int FLAG = 1
替换为bool FLAG = true
,将fprintf()
替换为std::cout
语句,就是这样。
如果您需要使用std::string
来完成相同的工作,只需简单地获取这些字符串的数组,默认将标志设置为 true,遍历每个字符串,并匹配第一个字符串的首字母等于其他人最终会在发现有缺陷的字符串后立即将标志标记为假。
该程序将显示(如果相同的初始与如果不是):
The strings have the same initial letters.
Not all strings have the same initial letters.
您不需要使用嵌套的 for 循环。而是以这种方式修改您的代码
for(int i = 0;i < size_arr - 2;i++){
f1 = (*str[i])[0];
f2 = (*str[i+1])[0];
if( f1!=f2 ){
printf("not same characters at first position");
break;
flag=1;
}
}
if(flag==0)printf("same characters at first position");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.