给定一行长度不超过 100 的非空字符串,请你求出它的具体长度。
输入一行,表示一个字符串。注意字符串中可能包含空格。
输出一个整数,表示它的长度。
1≤字符串长度≤100,字符串末尾无回车
I love Beijing.
15
cstring
函数库(C 风格字符串处理)cstring
是 C++ 中用于操作 C 风格字符串(以 \0
结尾的字符数组)的标准库。
主要包含以下常用函数:
strlen()
:返回字符串的长度(不包括结尾的 \0
)。strcat()
:将源字符串拼接到目标字符串的末尾(需确保目标空间足够)。strcpy()
:将源字符串复制到目标字符数组中(需确保目标空间足够)。strcmp()
:比较两个字符串,返回 0
表示相等,非 0
表示不相等(按字典序)。一句话总结:strlen
测长度,strcat
拼接,strcpy
复制,strcmp
比较。
#include
#include
using namespace std;
int main() {
char str1[20] = "Hello";
char str2[] = "World";
// 字符串长度(不包括 '\0')
cout << strlen(str1) << endl; // 输出 5
// 字符串拼接(str1 必须有足够空间)
strcat(str1, " ");
strcat(str1, str2); // str1 变为 "Hello World"
cout << str1 << endl;
// 字符串复制
char str3[20];
strcpy(str3, str1); // str3 变为 "Hello World"
cout << str3 << endl;
// 字符串比较
if (strcmp(str1, str3) == 0) {
cout << "str1 和 str3 相同" << endl;
}
return 0;
}
getline(cin, str)
(C++ 字符串输入)getline
是 C++ 标准库
提供的函数,用于从输入流(如 cin
)中读取一行文本,存储到 string
对象中。
#include
#include
using namespace std;
int main() {
string str;
// 读取一行(包括空格,直到遇到换行符)
cout << "请输入一行文本: ";
getline(cin, str);
cout << "你输入的是: " << str << endl;
return 0;
}
string
动态分配内存,无需担心缓冲区溢出。cin >> str
不同,getline遇到空格会停止)。getline(cin, str, ';')
会读取直到遇到 ;
。输入一行字符,长度不超过 100,请你统计一下其中的数字字符的个数。
输入一行字符。注意其中可能包含空格。
输出一个整数,表示数字字符的个数。
I am 18 years old this year.
2
#include
#include
using namespace std;
int main()
{
string str;
getline(cin,str);
int count=0;
for(int i=0;i='0'&&str[i]<='9')
{
count++;
}
}
cout<
给定两个长度相同的字符串 aa 和字符串 bb。
如果在某个位置 ii 上,满足字符串 aa 上的字符 a[i]a[i] 和字符串 bb 上的字符 b[i]b[i] 相同,那么这个位置上的字符就是匹配的。
如果两个字符串的匹配位置的数量与字符串总长度的比值大于或等于 kk,则称两个字符串是匹配的。
现在请你判断给定的两个字符串是否匹配。
第一行包含一个浮点数 kk,第二行包含字符串 aa,第三行包含字符串 bb。
输入的字符串中不包含空格。
如果两个字符串匹配,则输出 yes
。
否则,输出 no
。
0≤k≤10≤k≤1,
字符串的长度不超过 100100。
0.4
abcde
xbacd
no
#include
#include
using namespace std;
int main()
{
double k,count=0;
string s1,s2;
cin>>k>>s1>>s2;
for(int i=0;i=k)
{
cout<<"yes";
}
else{
cout<<"no";
}
return 0;
}
注意这里的字符串输入问题,如果直接使用getline是无效的,因为getline会取到回车,而正确的做法是用getchar()吞掉回车,然后再用getline输入。