給定駝峰式字串的句子大小寫


C++ 字串是由構成單詞的字元集合。它可能包含字母、數字,甚至特殊字元。字串的句子可以以不同的方式組合在一起,形成不同型別的表示形式。

字串的駝峰式命名法表示字串的方式,使其滿足以下兩個屬性:

  • 單詞連線在一起,沒有空格字元。

  • 每個單詞的第一個字母都儲存為大寫。

因此,這種表示形式中的大寫字母可以用來分隔不同的單詞。這種表示形式不容易閱讀,但在程式設計領域被廣泛使用。

另一種字串表示形式是句子大小寫,其中單詞之間用空格字元分隔,除了第一個單詞之外,所有單詞都以小寫字母開頭。

在以下問題中,必須將給定字串的駝峰式命名法轉換為句子大小寫表示形式。

一些說明問題陳述的示例如下:

示例

示例 1 - str : IdentifyThe@abc

輸出:Identify the@abc

說明:特殊字元也按原樣列印

示例 2 - str : ThisIsCamelCase

輸出:This is camel case

說明:在輸出過程中,第一個字母按原樣列印。

此問題可以透過字元大小寫檢查,然後根據需要將其轉換為相反的大小寫來解決。

演算法

  • 步驟 1 - 使用 for 迴圈遍歷提供的輸入字串。

  • 步驟 2 - 如果指標位於第一個字元處,則按原樣列印。

  • 步驟 3 - 對於其餘字元,如果找到大寫字母,則首先顯示空格字元。然後將字母轉換為小寫並顯示。

  • 步驟 4 - 否則,如果列印任何小寫字元,則按原樣列印。步驟 5 - 否則,任何特殊字元都按原樣列印。

示例

以下程式碼片段以駝峰式 C++ 字串為例,並將其分別轉換為句子大小寫:

//including the required libraries
#include <bits/stdc++.h>
using namespace std;

//convert camelcase string to sentence case respectively
void sentenceCase(string str){

   //getting the length of string
   int len = str.length();

   //iterating over the string
   for(int i=0;i<len;i++) {

      //printing the first character of the string
      if(i==0){
         cout << str[0];
      } else {

         //check if current character is in upper case convert to lower case and insert a space before it to separate the words
         if (str[i] >= 'A' && str[i] <= 'Z'){

            //printing a space before character
            cout << " " ;
            char ch = (char)tolower(str[i]);

            //printing the character in lower case
            cout << ch;
         }

         //if character already in lower case print as it is
         else
            cout << str[i];
      }
   }
}
//calling the method
int main(){

   //sample string
   string s = "ConvertCamelCaseToSentenceCase";
   cout<<"Entered String :"<<s;
   cout<<"\nConverted String:";

   //print the sentence case
   sentenceCase(s);
   return 0;
}

輸出

Entered String :ConvertCamelCaseToSentenceCase
Converted String:Convert camel case to sentence case

結論

在字串的情況下,可以輕鬆執行大小寫轉換。字串的句子大小寫增強了可讀性。它透過用空格分隔單詞使其易於理解。上述方法的時間複雜度在最壞情況下為 O(n),其中 n 是字串的長度。因此,演算法線上性時間內工作。上述演算法的空間複雜度為 O(1),本質上是常數。

更新於: 2023年3月15日

665 次檢視

開啟您的 職業生涯

透過完成課程獲得認證

開始
廣告