【问题标题】:Capitalizing individual characters in string array将字符串数组中的单个字符大写
【发布时间】:2015-08-11 07:00:50
【问题描述】:

我必须将字符串数组中的名字和姓氏大写,但在将字符串值输入数组后,我一直在纠结如何访问特定值。

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

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.   

【问题讨论】:

  • 你能发布你的main()函数吗?

标签: c++ arrays string


【解决方案1】:

试试这个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]);
        }

    }
}

【讨论】:

  • 这是我在使用您的重新格式化方法后得到的编译器错误。我仍然遇到同样的错误。从 std::string 类型的临时对象对 std::string 类型的非常量引用的初始化无效
  • 如果我不得不猜测,这可能是因为您在将 string[] 传递给您的 read() 函数之前还没有初始化它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多