驼峰式序列中的单词数
CamelCase 是一个或多个单词的序列,具有以下属性:
- 它是一个或多个由英文字母组成的单词的串联。
- 第一个单词中的所有字母都是小写的。
- 对于随后的每个单词,第一个字母为大写字母,其余字母为小写字母。
给定一个表示为字符串的 CamelCase 序列。任务是找出 CamelCase 序列中的单词数。
例子:
Input : str = "geeksForGeeks"
Output : 3
Input : str = "iGotAnInternInGeeksForGeeks"
Output : 8
方法:由于已知序列是CamelCase,所以可以说序列中单词的个数会比大写字母的个数多一个。
- 将序列从第 2 个字母迭代到序列的末尾。
- 在第 1 步迭代期间,单词数将等于大写字母 +1。
下面是上述方法的实现:
C++
// CPP code to find the count of words
// in a CamelCase sequence
#include
using namespace std;
// Function to find the count of words
// in a CamelCase sequence
int countWords(string str)
{
int count = 1;
for (int i = 1; i < str.length() - 1; i++) {
if (isupper(str[i]))
count++;
}
return count;
}
// Driver code
int main()
{
string str = "geeksForGeeks";
cout << countWords(str);
return 0;
}
Java
// Java code to find the count of words
// in a CamelCase sequence
class solution
{
// Function to find the count of words
// in a CamelCase sequence
static int countWords(String str)
{
int count = 1;
for (int i = 1; i < str.length() - 1; i++) {
if (str.charAt(i)>=65&&str.charAt(i)<=90)
count++;
}
return count;
}
// Driver code
public static void main(String args[])
{
String str = "geeksForGeeks";
System.out.print( countWords(str));
}
}
//contributed by Arnab Kundu
Python3
# Python code to find the count of words
# in a CamelCase sequence
# Function to find the count of words
# in a CamelCase sequence
def countWords(str):
count = 1
for i in range(1, len(str) - 1):
if (str[i].isupper()):
count += 1
return count
# Driver code
str = "geeksForGeeks";
print(countWords(str))
# This code is contributed
# by sahishelangia
C#
// C# code to find the count of words
// in a CamelCase sequence
using System;
class GFG
{
// Function to find the count of words
// in a CamelCase sequence
static int countWords(String str)
{
int count = 1;
for (int i = 1; i < str.Length - 1; i++)
{
if (str[i] >= 65 && str[i] <= 90)
count++;
}
return count;
}
// Driver code
public static void Main(String []args)
{
String str = "geeksForGeeks";
Console.Write(countWords(str));
}
}
// This code contributed by Rajput-Ji
Javascript
输出:
3