简体   繁体   中英

How to convert string to Title Case?

I am trying to build a Title Case function that takes a string, and returns the string in title-case.

Basically, my idea was to manually upper case the first char of the string and do the rest by checking if there is 'space' before the character.

So far this is my effort.

string Title_Case(const string A) {
  char First_capital = static_cast<int>(A[0]) - 32;
  string B;
  B[0] = First_capital;

  for (int i = 1; i < A.size(); i++) {
    if (A[i - 1] == ' ' && A[i] >= 'a' && A[i] <= 'z') {
      char capital = A[i] - ('a' - 'A');
      B += capital;
      continue;
    } else
      B = B + A[i];
  }

  return B;
}

@QuatCoder's answer is correct. You are accessing the B[0] even though the length of the B string is zero.

But @Meharjeet Singh: Edge conditions have not been handled by your function.

Pre conditions for the function above:

  1. The first letter of the input string parameter is always a lowercase letter.
  2. The first letter of the input string parameter is not a white space.

Edge conditions have been handled in the below function

string Title_Case(const string A) {
    
    string B = "";

    int pos = 0;
    int pre_pos = 0;

    pos = A.find(' ', pre_pos);

    while (pos != string::npos)
    {
        string sub = "";

        sub = A.substr(pre_pos, (pos - pre_pos));

        if (pre_pos != pos)
        {
            sub = A.substr(pre_pos, (pos - pre_pos));
        }
        else 
        {
            sub = A.substr(pre_pos, 1);
        }
        
        sub[0] = toupper(sub[0]);
        B += sub + A[pos];

        if (pos < (A.length() - 1))
        {
            pre_pos = (pos + 1);
        }
        else
        {
            pre_pos = pos;
            break;
        }

        pos = A.find(' ', pre_pos);

    }

    string sub = A.substr(pre_pos, string::npos);
    sub[0] = toupper(sub[0]);
    B += sub;
    
    return B;
}

In the function the string B is an empty string so there is no B[0], however you can assign a char to a string so the following should work

string Title_Case (const string A){
        
        char First_capital = static_cast<int>(A[0]) - 32;
        string B;
        B = First_capital; 
        
        for ( int i =1; i <A.size(); i++){
                if( A[i-1] == ' ' &&  A[i] >= 'a' && A[i] <= 'z'){
                                char capital = A[i] - ( 'a' - 'A');
                                B += capital;
                                continue;
                        }
                else
                        B = B + A[i];
        }
        
        return B;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM