简体   繁体   English

除姓氏外,我该如何取名字的所有部分的首字母?

[英]How do i take the initials of all the parts of one's name except the last name?

Hi i am trying to write a c++ program where the user will enter a name lets say for example: Tahmid Alam Khan Rifat and the computer will print the formatted version of the name which in this case will be: Mr. TAK Rifat. 嗨,我正在尝试编写一个c ++程序,用户将输入一个名称,例如:Tahmid Alam Khan Rifat,计算机将打印该名称的格式版本,在这种情况下,它将是:TAK Rifat先生。 I have included the code below. 我已包含以下代码。 You will be able to see that I got close but still not exactly what i wanted. 您将能够看到我已经接近了,但仍然不是我想要的。 Please help. 请帮忙。

#include<iostream>

#include<string>

using namespace std;

class myclass{

private:

string name,temp;

    string p;

int i,j,sp;

public:
    void work(){

        cout << "Enter the name of the male student: ";
        getline(cin,name);
        cout << endl;
        cout << "The original name is: ";
        cout << name;
        cout << endl << endl;

        cout << "The formatted name is: " << "Mr." << name[0] << ".";
        for(i=0;i<name.size();i++){
            if(name[i]==' '){
                sp=i;
                for(j=sp+1;j<=sp+1;j++){
                temp=name[j];
                cout << temp << ".";
            }
        }
    }
        for(i=sp+2;i<name.size();i++){
            cout << name[i];
        }
        cout << endl;

    }
};

int main(){
    myclass c;
    c.work();
}

I hope this helps :) It is probably a simpler version (originally I wrote this in C, you could easily convert it to C++ though, since the logic remains the same). 我希望这会有所帮助:)它可能是一个简单的版本(本来我用C编写的,但是由于逻辑保持不变,您可以轻松地将其转换为C ++)。 I have accepted the name and then inserted a space at the beginning of the string and one more space at the end, before the NULL character ('\\0') 我已经接受了该名称,然后在字符串的开头插入了一个空格,在NULL字符('\\ 0')之前的末尾又插入了一个空格。

The program checks for a space. 程序检查空格。 When it encounters one, it checks for the next space that occurs in the string. 遇到一个空格时,它会检查字符串中下一个空格。 Now occurrence of this space helps us to identify an important determining factor as to what the next action should be. 现在,该空间的出现有助于我们确定下一个动作应该是什么的重要决定因素。

See, if there is an null character after this subsequent space, then we can conclude that the subsequent space was the one we inserted at the end of the string. 看,如果在此后续空格之后有一个空字符,那么我们可以得出结论,该后续空格是我们在字符串末尾插入的空格。 That is, the space which occurs after the primary space, which came before the surname. 也就是说,该空间位于主要空间之后,该空间位于姓氏之前。 Bingo! 答对了! You get the precise index of the array, from where the surname starts! 您将从姓氏开始的地方获得数组的精确索引! :D :d

Looks long, but really is simple. 看起来很长,但确实很简单。 Good luck! 祝好运!

    #include<stdio.h>
    #include<string.h>
    void main()
    {
        char str[100]; /*you could also allocate dynamically as per your convenience*/
        int i,j,k;
        printf("Enter the full name: ");
        gets(str);

        int l=strlen(str);

        for(i=l;i>=0;i--)
        {
         str[i+1]=str[i]; //shifting elements to make room for the space 
        }

        str[0]=' ';                   //inserting space in the beginning
        str[l+1]=' '; str[l+2]='\0';  //inserting space at the end

        printf("The abbreviated form is:\n");



        for(i=0;i<l+1;i++)                            //main loop for checking
        {
           if(str[i]==' ')                            //first space checker
            {
                for(j=i+1; str[j]!=' ';j++)           //running loop till subsequent space
                {
                }
                if(str[j+1]!='\0')                    //not the space after surname
                {
                    printf("%c.",str[i+1]);           //prints just the initial
                }
                else
                for(k=i+1;str[k]!='\0';k++)           //space after surname
                {
                    printf("%c", str[k]);             //prints the entire surname
                }
            }
        }



    }

Change your loop to the following:- 将循环更改为以下内容:

for(i=0;i<name.size();i++)
{
    if(name[i]==' ')
    {
        initial = i + 1;          //initial is of type int.
        temp = name[initial];     //temp is char.
        cout << temp << ".";
    }
}

Try ravi's answer to make your code work, but I wanted to point out that there are more intuitive ways to program this which would make maintenance and collaboration easier in the future (always a good practice). 尝试用ravi的答案使您的代码正常工作,但我想指出,有更直观的方法对此进行编程,这将使将来的维护和协作更加容易(始终是一种好习惯)。

You can use an explode() implementation (or C's strtok()) to split the name string into pieces. 您可以使用explode()实现(或C的strtok())将名称字符串拆分为多个部分。 Then just use the first character of each piece, disregarding the last name. 然后,只需使用每个作品的第一个字符,而不必考虑姓氏。

I think your question has already been answered. 我认为您的问题已经得到解答。 But in the future you could consider splitting up your program into more simple tasks, which makes things easier to read. 但是在将来,您可以考虑将程序分成更简单的任务,这使事情更容易阅读。 Coupled with descriptive variable and function names, it can make a program easier to comprehend, and therefore to modify or fix later on. 结合描述性的变量和函数名称,它可以使程序更易于理解,因此可以在以后进行修改或修复。 Disclaimer - I am a beginner amateur programmer and this is just for ideas: 免责声明-我是一名初学者业余程序员,这仅是一些想法:

#include <iostream>
#include <iterator>
#include <sstream>
#include <vector>

// I got this function from StackOverflow somewhere, splits a string into
// vector of desired type:
template<typename T>
std::vector<T> LineSplit(const std::string& line) {
    std::istringstream is(line);
    return std::vector<T>(std::istream_iterator<T>(is), std::istream_iterator<T>());
}
class Names {
 private:
    std::vector<std::string> full_name_;

    void TakeInput() {
        std::cout << "Enter the name of the male student: " << std::endl;
        std::string input;
        getline(std::cin,input);
        full_name_ = LineSplit<std::string>(input);
    }
    void DisplayInitialsOfFirstNames() const {
        std::cout << "Mr. ";
        for (std::size_t i = 0; i < full_name_.size()-1; ++i) {
            std::cout << full_name_[i][0] << ". ";
        }
    };
    void DisplayLastName() const {
        std::cout << full_name_.back() << std::endl;
    }
public:
    void work() {
        TakeInput();
        DisplayInitialsOfFirstNames();
        DisplayLastName();
    };
};
int main(){
    Names n;
    n.work();
}

I guess the easiest way to solve this is to tokenize your string, print the first character from it, except from the last, where you print its full size. 我猜想解决此问题的最简单方法是标记字符串,从中打印第一个字符,但从最后一个开始打印完整字符。

To tokenize, you can do something like that: 要标记化,您可以执行以下操作:

std::vector<std::string> tokenize(std::istringstream &str)
{
    std::vector<std::string> tokens;
    while ( !str.eof() ) {
            std::string tmp;
            str >> tmp;
            tokens.push_back(tmp);
    }
    return tokens;
}

Now you can easily transverse the tokens: 现在您可以轻松地遍历令牌:

int main()
{
    std::string name;

    cout << "Enter the name of the male student: ";
    getline(cin,name);
    cout << endl;

    cout << "The original name is: ";
    cout << name;
    cout << endl << endl;

    std::istringstream str(name);

    std::vector<std::string> tokens = tokenize(str);

    for ( int i = 0 ; i < tokens.size() - 1; ++i)
            std::cout << tokens[i][0] << ". ";

    cout << tokens[tokens.size() - 1] << endl;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用2个for循环获取存储在数组中的所有名字首字母? - How to get all initials of name stored in an array using 2 for loops? 我如何从他们的全名的用户那里得到输入,然后 output 他们的名字和姓氏分开? (C++) - How do I take input from the user of their full name, and then output their first name and last name seperately? (C++) 带有QFileSystemModel的QTreeView:如何删除除“名称”之外的所有列? - QTreeView with QFileSystemModel: How can I remove all columns except “Name”? 如何按作者的姓氏但有多位作者搜索图书清单类别? - How do I search a book list class by the author's last name but with multiple authors? 如果最后一个地址是0xFFFFFFFF,如何取一个数组末尾的地址? - How do I take the address of one past the end of an array if the last address is 0xFFFFFFFF? 如何从控制台输入学生的全名(包括空格)并将其存储在c ++中的数组中? - How do I take full name of students(including space) as input from console and store it in an array in c++? 我被困在如何使用 C++ 中一个人的名字和姓氏在双向链表中进行排序算法 - I'm stuck on how to make a sorting algorithm in a doubly linked list using a person's first name and last name in C++ 如何在不使用variable_name.at()的情况下引用字符串的最后一个字符? - How do I reference the last character of a string without using variable_name.at()? 如何替换字符串中除一个以外的所有单词 - How can I replace all words in a string except one 如何将除第一个参数以外的所有参数扩展到可变参数宏? - How do I expand all except for the first parameter to a variadic macro?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM