统计英文句子中的字符个数

#include<iostream>
#include <string>
using namespace std ;
int count(string Str)  //统计字符串个数的函数
{
	int i = 0, cnt = 0;
	for (i=0; i<Str.length(); i++)
	{
		if (Str[i]>='a' && Str[i]<='z' || Str[i] >='A' && Str[i]<='Z' )
		cnt++;
	}
	cout<<"your str:"<<endl;  //展示输入内容
	cout << "str="<<Str<<endl ;
	return cnt;
}
void main()
{
	string Str;
	char ch;
	cout<<"input str:"<<endl;  //输入
	getline(cin , Str );
	int a = count(Str);
	cout << "字母个数:" <<a<<endl;
}

 

在 Java 中统计英文句子中的单词个数,通常可以采用以下步骤: 1. **准备字符串**:首先,你需要将输入的英文句子存储在一个 `String` 变量中。 ```java String sentence = "This is a sample sentence for word count."; ``` 2. **移除标点和空格**:使用正则表达式可以去除句子中的标点符号和多余的空格。你可以创建一个新的字符串,只包含字母和数字。 ```java String cleanedSentence = sentence.replaceAll("[^a-zA-Z0-9\\s]", "").toLowerCase(); ``` 这里我们使用了 `replaceAll` 函数,第一个参数是一个正则表达式匹配非字母、非数字和非空格的字符,第二个参数是替换它们为空字符串。 3. **分割成单词数组**:接下来,我们将清洗后的字符串按空格分割成单词数组。 ```java String[] words = cleanedSentence.split("\\s+"); ``` `split("\\s+")` 分割字符串,`\s+` 表示一个或多个连续的空格。 4. **计数单词**:遍历数组并累加单词数量。 ```java int wordCount = words.length; ``` 5. **结果输出**:最后,输出单词总数。 ```java System.out.println("The sentence contains " + wordCount + " words."); ``` 完整代码如下: ```java public class Main { public static void main(String[] args) { String sentence = "This is a sample sentence for word count."; String cleanedSentence = sentence.replaceAll("[^a-zA-Z0-9\\s]", "").toLowerCase(); String[] words = cleanedSentence.split("\\s+"); int wordCount = words.length; System.out.println("The sentence contains " + wordCount + " words."); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值