单词首字母大写c++
时间: 2023-12-03 09:40:03 浏览: 31
以下是C++中将每个单词的首字母改为大写并去掉多余空格的代码:
```cpp
#include <iostream>
#include <string>
#include <cctype> // 包含toupper函数
using namespace std;
int main() {
string str;
getline(cin, str); // 输入一行字符串
bool flag = true; // 标记是否为单词的第一个字符
for (int i = 0; i < str.length(); i++) {
if (isspace(str[i])) { // 如果是空格
flag = true; // 下一个字符为单词的第一个字符
cout << " "; // 输出一个空格
} else if (flag) { // 如果是单词的第一个字符
cout << (char)toupper(str[i]); // 输出大写字母
flag = false; // 下一个字符不是单词的第一个字符
} else { // 如果是单词的其他字符
cout << (char)tolower(str[i]); // 输出小写字母
}
}
cout << endl;
return 0;
}
```
相关问题
c++将字符串中每个单词的首字母改为大写字母
要将字符串中每个单词的首字母改为大写字母,可以使用Python中的内置函数和方法来实现。首先,将字符串分割成单词列表,然后将每个单词的首字母改为大写,最后将修改后的单词列表重新连接成字符串。
以下是一个简单的实现:
```
def capitalize_words(string):
# 将字符串分割成单词列表
words = string.split()
# 将每个单词的首字母改为大写
capitalized_words = [word.capitalize() for word in words]
# 将修改后的单词列表重新连接成字符串
capitalized_string = ' '.join(capitalized_words)
return capitalized_string
```
使用该函数,可以将字符串中每个单词的首字母改为大写字母。例如:
```
string = "hello world"
capitalized_string = capitalize_words(string)
print(capitalized_string)
# 输出: "Hello World"
```
这个函数首先使用`split()`方法将字符串分割成单词列表`words`,然后使用列表推导式将每个单词的首字母改为大写,生成一个新的列表`capitalized_words`。接着,使用`join()`方法将修改后的单词列表重新连接成字符串`capitalized_string`。最后,将修改后的字符串返回。
C++实现首字母大写、过滤多余空格后输出
以下是C语言实现首字母大写、过滤多余空格后输出的代码:
```c
#include <stdio.h>
#include <ctype.h>
void capitalize(char *str) {
int i = 0;
while (str[i] != '\0') {
if (i == 0 || str[i-1] == ' ') {
str[i] = toupper(str[i]);
} else {
str[i] = tolower(str[i]);
}
i++;
}
}
void remove_extra_spaces(char *str) {
int i, j;
for (i = j = 0; str[i]; i++) {
if (!isspace(str[i]) || (i > 0 && !isspace(str[i-1]))) {
str[j++] = str[i];
}
}
if (j > 0 && isspace(str[j-1])) {
j--;
}
str[j] = '\0';
}
int main() {
char str[1000];
printf("Enter a string: ");
fgets(str, 1000, stdin);
capitalize(str);
remove_extra_spaces(str);
printf("Output: %s\n", str);
return 0;
}
```
这个程序要求用户输入一个字符串,然后对其进行首字母大写和过滤多余空格的处理,最后输出处理后的字符串。
首先,我们定义了两个函数:`capitalize()`和`remove_extra_spaces()`。
`capitalize()`函数用于将字符串的每个单词的首字母大写,其实现方式是遍历字符串中的每个字符,如果当前字符是单词的第一个字符或者前一个字符是空格,则将该字符转换为大写,否则转换为小写。
`remove_extra_spaces()`函数用于删除字符串中多余的空格,其实现方式是遍历字符串中的每个字符,如果当前字符不是空格或者前一个字符也不是空格,则将该字符保留,否则忽略该字符。最后,如果字符串末尾有多余的空格,则删除它们。
在`main()`函数中,我们首先使用`fgets()`函数从标准输入中读取一行字符串,接着调用`capitalize()`和`remove_extra_spaces()`函数对该字符串进行处理,最后输出处理后的字符串。
注意,在使用`fgets()`函数读取字符串时,我们限定了字符串的长度不能超过1000个字符。如果用户输入的字符串超过了这个长度,可能会导致程序出现错误。如果需要处理更长的字符串,可以根据实际情况自行调整数组大小。