C++ 对至少有K个字符的所有单词进行首字母大写
在英语中,写句子时我们需要以大写字母开头,而对于任何城市/人名等,我们都以大写字母开头。在这个问题中,我们给定一个字符串和一个数字,我们必须更新给定字符串中所有单词的第一个字符,如果它们的大小不小于k。另外,如果单词的大小超过k且它们的第一个字符已经大写,则我们将保留它不变。
示例示例
输入
string str = “this is the given string To change”
int k = 5
输出结果
this is the Given String To Change
输入
string str = “thisisthegivenstring”
int k = 8
输出
“Thisisthegivenstring”
简单的方法
在这个方法中,我们要遍历字符串并找出空白字符,因为每个空白字符后面都有一个新的单词。
首先,我们将创建一个指针,指向第一个字符,并有另一个指针遍历字符串,直到检测到空白字符或字符串的末尾。
我们将使用toupper()函数将字符串的第一个字符大写。如果第一个字符已经大写,则保持不变,否则将改变。
此外,可能会出现连续两个空白字符的情况,对此我们将检查两个指针是否在同一个位置,如果是,则不需要做任何更改,继续下一个字符。
示例
#include <bits/stdc++.h>
using namespace std;
// creating a function to change the given string
string changeString(string str, int k){
int len = str.length(); // storing the size of the given string
int ptr = 0; // pointer to point at the first character
for(int i=0; i<len; i++){
if(str[i] == ' '){
// if the pointer and the current pointer are in the same position either case of double whitespace characters or whitespace at the start of the string
if(i != ptr && i-ptr >= k){
str[ptr] = toupper(str[ptr]);
}
ptr = i+1;
}
}
// condition for the last word
if(ptr != len){
str[ptr] = toupper(str[ptr]);
}
return str;
}
int main(){
string str = "this is the given string To change"; // given string
int k = 5; // given number
// calling the function
cout<<changeString(str, k)<<endl;
return 0;
}
输出结果
this is the Given String To Change
时间和空间复杂度
以上代码的时间复杂度为O(N),其中N是给定字符串的长度。
以上代码的空间复杂度为O(1),因为我们没有使用任何额外的空间并且改变了给定的字符串。
使用C++的StringStream类
StringStream是C++编程语言中定义的一个类,用于将字符串作为字符流进行处理。我们可以使用“<<”字符将单词以流的形式获取,每次一个单词将被获取并存储在一个字符串变量中。
在这个程序中,我们使用了相同的概念,创建了一个stringstream变量来存储给定的字符串,然后创建了一个字符串变量来从字符串中获取单词,并创建了另一个变量来存储答案。
我们使用while循环使用“<<”从流中提取单词的顺序,并且如果需要,我们将每个单词的第一个字符大写。
此外,我们将每个单词存储在字符串中,并且我们需要在每个单词后面添加额外的空格,并将返回该答案。
示例
#include <bits/stdc++.h>
using namespace std;
// creating a function to change the given string
string changeString(string str, int k){
stringstream s(str); //creating the stringstream variable
string ans = ""; // string to store the answer
string cur_word; // string to get the words from the string stream
while( s >> cur_word){
// if length of this word is less than k continue otherwise update the value of the first character if needed
if(cur_word.length() < k){
ans += cur_word;
}
else{
cur_word[0] = toupper(cur_word[0]);
ans += cur_word;
}
// adding space after each word
ans += " ";
}
ans.pop_back(); // removing the last added space
return ans; //return the final string.
}
int main(){
string str = "this is the given string To change"; // given string
int k = 5; // given number
// calling the function
cout<<changeString(str, k)<<endl;
return 0;
}
输出
this is the Given String To Change
时间与空间复杂度
以上代码的时间复杂度为O(N),其中N是给定字符串的长度。
以上代码的空间复杂度为O(N),因为我们在这里使用了额外的空间,即一个字符串来存储流和答案。
结论
在本教程中,我们实现了一个程序,如果给定字符串的长度大于给定数值,则将每个单词的首字符大写。我们实现了两种方法:一种是使用toupper() C++函数来将每个单词的第一个字符大写,并通过使用两个指针遍历字符串。在第二种方法中,我们使用了stringstreamc++库来获取每个单词。