检索字符串的第一个字符并在 C++ 中按字母顺序比较它

Retrieving the first char of a string and comparing it alphabetically in C++

我是一名通过教程学习 C++ 的新手程序员,我想知道如何获取一个字符串,获取它的第一个字母,将它与其他 2 个字符串的第一个字母进行比较,然后按字母顺序对它们进行排序。我不想为我编写代码。我想了解如何执行此操作,因为其他解决方案很难理解。

我知道字符串只是 char 数组,所以应该有一种方法来获取第一个索引。

更新

所以这是我的尝试:

#include <iostream>
#include <string>
using namespace std;

void valueOutput(string firstName, string secondName, string thirdName){
    cout << "\n";
    cout << firstName << endl;
    cout << secondName << endl;
    cout << thirdName << endl;
}

int main(){
    string name1, name2, name3;

    cout<<"Enter 3 names: "<<endl;

    cin>>name1;
    cin>>name2;
    cin>>name3;

    if(
       (name1[0] < name2[0] && name2[0] < name3[0]) 
    || (name1[0] < name3[0] && name3[0] < name2[0])
    || (name2[0] < name1[0] && name1[0] < name3[0])
    || (name2[0] < name3[0] && name3[0] < name1[0])
    || (name3[0] < name1[0] && name1[0] < name2[0]) 
    || (name3[0] < name2[0] && name2[0] < name1[0]))
    {valueOutput(name1, name2, name3);}
    else{
        return 0;
    }

}

我的输入是: 斯坦贝克 海明威 菲茨杰拉德

但输出的顺序完全相同。我想按字母顺序对它们进行排序。

I know that strings are just arrays of char so there should be a method to get the first index.

你的意思似乎是字符串文字。

如果你有三个这样的声明

char *s1 = "Onur";
char *s2 = "Ozbek";
char *s3 = "Hello";

然后你可以通过以下方式比较字符串文字的第一个字符

if ( s1[0] == s2[0] )

if ( *s2 == *s3 )

如果您声明数组而不是指针,则可以使用相同的表达式

char s1[] = "Onur";
char s2[] = "Ozbek";
char s3[] = "Hello";

事实上你甚至可以使用下面的表达式

if ( "Onur"[0] == "Ozbek"[0] )

if ( *"Onur" == *"Ozbek" )

甚至喜欢

if ( 0["Onur"] == 0["Ozbek"] )

直接比较字符串文字的第一个字符。

#include <iostream>

int main() {
    std::string str1, str2, str3;
    std::cout << "Enter First String  :  ";
    getline(std::cin, str1);
    std::cout << "Enter Second String  :  ";
    getline(std::cin, str2);
    std::cout << "Enter Third String  :  ";
    getline(std::cin, str3);
    // The code is descriptive by itself till now

    // Now we gonna compare each of them.
    if(str1[0] < str2[0]) {  // Once the control flow get inside this if statement that means str1 is smaller than str2
        if (str1[0] < str3[0] && str3[0] < str2[0]) 
            std::cout << str1 << std::endl << str3 << std::endl << str2; // In here we get that str1 is smaller than str3 (and str1 is smaller than str2 as well), so the smallest is str1 and we print that. and then we compared str3 with str 2, if str3 is smaller than str2 then we will print secondly str3 and thirdly str2.
        else if (str1[0] < str3[0] && str2[0] < str3[0])
            std::cout << str1 << std::endl << str2 << std::endl << str3; // Here we get that str1 is smaller than str2 and str3 so we firstly print str1 and then we compared str2 with str3, if str2 is smaller than str3 then we will secondly print str2 and thirdly print str3.
        else
            std::cout << str3 << std::endl << str1 << std::endl << str2; // Now both the conditions mentioned above are wrong that means str3 is smaller than str1 and from the very first condition, we get that str1 is smaller than str2. That means smallest is str3 then str1 then str2 and we printed all of them in this order.
    } else { // else will be executed when str2 will be smaller than str1. So till now we get that str2 is smaller than str1. Now remember that str2 is smaller than str1.
        if (str2[0] < str3[0] && str3[0] < str1[0])
            std::cout << str2 << std::endl << str3 << std::endl << str1; // Now here str2 proved to be smaller than str3 (and we already know that str2 is smaller than str1), So str2 is the smallest and we printed firstly str2. Then we compared str3 with str1, if str3 is smaller than str1 then we will secondly print str3 and thirdly print str1.
        else if (str2[0] < str3[0] && str1[0] < str3[0])
            std::cout << str2 << std::endl << str1 << std::endl << str3;  // Now here str2 proved to be smaller than str3 (and we already know that str2 is smaller than str1), So str2 is the smallest and we printed firstly str2. Then we compared str1 with str3, if str1 is smaller than str3 then we will secondly print str1 and thirdly print str3.
        else
            std::cout << str3 << std::endl << str2 << std::endl << str1; // Now both the above conditions are false that means str3 is smaller than str2 and as we know that str2 is smaller than str1, that means str3 is the smallest, so we firstly printed str3 and then str2 and at last str1.
    }
return 0;
}

这是完整的代码,我认为你可以理解它...如果你不能理解任何特定行,你可以随意询问..

您可以使用 operator[indexNumber]

获得特定位置

但是如果你想排序,你应该使用来自#include <algorithm>std::sort 和一个字符串向量 std::vector<std::string>

//编辑:注意 a 和 A 对于排序或比较是不同的,搜索 ascii table

我会给出一个代码示例,如果您不想要解决方案,请不要继续阅读

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main()
{
  std::vector<std::string> stringArray;
  stringArray.reserve(4);
  stringArray.push_back("Hi");
  stringArray.push_back("Hello world");
  stringArray.push_back("New c++");
  stringArray.push_back("Animal");
  std::sort(stringArray.begin(), stringArray.end());
  for(auto&a : stringArray)
  {
    std::cout << a << '\n';   
  }

}

如果您了解 STL 容器 std::vector,这项工作就会容易得多。 如果你正在寻找简单的东西,就在这里,希望评论能帮助你理解。

#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
int main()
{
    int size = 3;                 //size of your vector
    std::vector<std::string> vec; //initialize the vec with string type
    vec.reserve(size);            // just to reserve the memory

    // input iterator takes strings from std console-size times-and put it back in to vec
    std::copy_n(std::istream_iterator<std::string>(std::cin), size, back_inserter(vec));

    // this will do your job as per requirement
    std::sort(vec.begin(), vec.end());

    // just to print the result
    std::copy(vec.begin(),vec.end(), std::ostream_iterator<std::string>(std::cout,"\n"));
    return 0;
}

假设您的字符串命名为 st1 、 st2 、 st3 并且您想对它们执行上述操作。

一个快速的方法是使用 std::vector。您将所有字符串第一个索引值推送到向量,然后排序 it.A 明确的实现将是这样的:

  vector<char> v;
  v.push_back(st1[0]);
  v.push_back(st2[0]);
  v.push_back(st3[0]);

  sort(v.begin() , v.end());

您可以在此处阅读有关矢量的更多信息:https://www.geeksforgeeks.org/vector-in-cpp-stl/

想通了。我基本上必须在每个 if 语句中调用该函数:

#include <iostream>
#include <string>
using namespace std;

void valueOutput(string firstName, string secondName, string thirdName){
    cout << "\n";
    cout << firstName << endl;
    cout << secondName << endl;
    cout << thirdName << endl;
}

int main(){
    string name1, name2, name3;

    cout<<"Enter 3 names: "<<endl;

    cin>>name1;
    cin>>name2;
    cin>>name3;

    if(name1[0] < name2[0] && name2[0] < name3[0]){
        valueOutput(name1, name2, name3);
    }
    else if(name1[0] < name3[0] && name3[0] < name2[0]){
        valueOutput(name1, name3, name2);
    }
    else if(name2[0] < name1[0] && name1[0] < name3[0]){
        valueOutput(name2, name1, name3);
    }
    else if(name2[0] < name3[0] && name3[0] < name1[0]){
        valueOutput(name2, name3, name1);
    }
    else if(name3[0] < name1[0] && name1[0] < name2[0]){
        valueOutput(name3, name1, name2);
    } 
    else if(name3[0] < name2[0] && name2[0] < name1[0]){
        valueOutput(name3, name2, name1);
    }

}

如果你不想要代码,我会告诉你同样的逻辑。

1。哈希

您可以使用哈希对字符串进行排序。这背后的想法是 在第 (i) 个字符串的第一个字符的位置存储 i。 例如: 考虑你的字符串如下::: aaa, bbb, ccc

现在在位置[ith_string[0] - 'a'] you store i(这里0位置对应'a', 1位置对应'b',..等..

换句话说,您对每个字符串执行此操作 array[str1[0] - 'a'] = 1,依此类推。

所以你的数组看起来像这样:: array = {1, 2, 3}

然后您可以使用您存储在我们的散列数组中的位置打印字符串。 我知道这看起来有点难,但我建议你看一些关于散列的教程,你就会明白了。

2。排序

您也可以使用排序,但是您需要存储字符串的位置。您可以使用 pair 来存储字符串和字符串的位置。然后您可以使用@VaradBhatnagar 的解决方案对字符串进行排序,并根据位置,您可以按该顺序打印它。

如果您想知道我刚才说的内容,请参阅下面的代码以供参考。我相信你会明白这一点。(如果你不明白,请随时提出疑问)。

#include <bits/stdc++.h>
using namespace std;
void hashing(string str[], int n){
    int arr[26] = {0}; // Because there are only 26 alphabets
    for(int i = 0 ; i < n ; i++){
        arr[str[i][0] - 'a'] = i + 1; // we should not store 0, as 0 defines "there was no string starting from this alphaber" 
    }
    for(int i = 0 ; i < n ; i++){
        if(arr[i] != 0){
            cout << str[arr[i] - 1] << endl;
        }
    }
}   
void sorting(string str[], int n){
    std::vector<pair <char, int> > v;
    for (int i = 0 ; i < n ; i++){
        v.push_back(make_pair(str[i][0], i));
    }
    sort(v.begin(), v.end()); // this will sort on the basis of 1st argument in our pair
    for(int i = 0 ; i < n ; i++){
        cout << str[v[i].second] << endl;
    }
}
int main(int argc, char const *argv[])
{
    int n;
    string str[30]; // it can not be larger than 26, because of the question
    cin >> n;
    for(int i = 0 ; i < n ; i++){
        cin >> str[i];
    }
    cout << "Result of hashing" << endl;
    hashing(str, n);

    cout << "Result of sorting" << endl;
    sorting(str, n);

    return 0;
}

输入

3
cccc
bb  
aaaa 

输出

Result of hashing
aaaa
bb
cccc
Result of sorting
aaaa
bb
cccc

enter image description here假设您的 3 个名称是 name1、name2 和 name3,并且您知道字符串只是一个 char 数组,因此您可以使用其 Ascii 编号比较每个 char,并且不要忘记考虑大写字母和小写字母,因为它们在 ascii 中的区别是 32,而小写字母大于大写字母,因此您将像在代码中那样在它们之间进行转换。这里没有任何复杂的功能,所以很容易理解

#include <iostream>
using namespace std;

void comparing(string& name1,string& name2);
void comparing(string& name1,string& name2,string& name3);

int main(){
    string name1, name2, name3;
    cout<<"Enter 3 names: "<<endl;
    cin>>name1;
    cin>>name2;
    cin>>name3;
    comparing(name1,name2,name3);
}
void comparing(string& name1,string& name2)
{
    string t;
    for(int i=0;i<name1.size();i++){
        int x = (int)name1[i];
        int y = (int)name2[i];
        if(x<=97 && x>=122){
            x=x-32;
        }
        if(y<=97 && y>=122){
            y=y-32;
        }
        if(x>y){
            t=name1;
            name1=name2;
            name2=t;
            break;
        }}
}
void comparing(string& name1,string& name2,string& name3)
{
    comparing(name1,name2);
    comparing(name2,name3);
    comparing(name1,name3);
    comparing(name1,name2);
    cout << name1 << " " <<name2 << " " <<name3 <<endl;
}