簡體   English   中英

檢查字符串數組中所有字符串的第一個字符是否相同

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM