将字符串数组中的单个字符大写

Capitalizing individual characters in string array

本文关键字:字符 单个 字符串 数组      更新时间:2023-10-16

我必须在字符串数组中大写名字和姓氏,但是我被困在如何在我将字符串值输入到数组后访问特定值。

下面是我的两个函数,第一个函数将值读入两个单独的数组,第二个函数应该将名字和姓氏大写,同时将所有其他字符更改为小写。

void read(string names[],int DVDrent[],int& n)
{
   n=0;          // # of data calculated
   cin >> names[n] >> DVDrent[n]
   while(cin)
     {
       n++;
       cin >> names[n] >> DVDrent[n];
     }
}
void reformat(string& names)
{
    int nlen;
    nlen = names.length();
    names[0] = toupper(names[0]);
    for (int i=1; i<nlen; i++)
       {
           if (names[i] == ',')
           names[i+1] = toupper(names[i+1]);
           names[i+2] = tolower(names[i+2]);
       }
}

如果我只是将数据存储为字符串,则第二个函数可以工作。我现在卡住了,因为我不确定如何读取数组的特定字符。

作为参考,我输入的数据如下:

./a.out < data > output

数据:

smith,EMILY 3   
Johnson,Daniel 2   
williAMS,HanNAH 0   
joneS,Jacob 4   
bROwn,MicHAEL 5   
DAVIS,ETHAn 2   
millER,soPhiA 0   
TAYlor,matthew 1   
andERSON,aNNa 7   

期望输出:

Smith,Emily 3    
Johnson,Daniel 2   
William,Hannah 0   
.   
.   
.   
Anderson,Anna 7   
etc.   

为您的reformat()方法试试:

void reformat(string& names) {
    bool isUpper = true; // store if the next letter should be upper
    for(size_t i = 0; i < names.length(); ++i) {
        if (names[i] == ',') {
            isUpper = true; // if it's a comma, make the next letter upper
        }
        else if (isUpper) {
            names[i] = toupper(names[i]);
            isUpper = false; // make the next letter lower
        }
        else {
            names[i] = tolower(names[i]);
        }
    }
}