162 - 字符串
Time Limit: 1000 Memory Limit: 65535
Submit: 502 Solved: 269
Description
对于输入字符串s(假设字符串只包含字母构成的单词和空格),完成如下功能:
1. 统计该字符串中字母c出现的次数
2. 求该字符串的逆
3. 输出该字符串中子串str的所有位置(无需考虑子串叠加现象)
4. 将字符串中每个单词的第一个字母变成大写并输出
Input
字符串s
字母c
子串str
Output
c在s中出现的次数
s的逆
str在s中的所有位置
所有单词首字母大写后的字符串
Sample Input
I scream you scream we all scream for icecream
m
eam
Sample Output
4
maerceci rof maercs lla ew maercs uoy maercs I
5 16 30 43
I Scream You Scream We All Scream For Icecream
HINT
Pre Append Code
Post Append Code
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
String s = scan.nextLine();//!!!next方法与nextLine方法都可用于输入字符串,但next方法不能得到带空格的字符串,而nextLine()方法返回的是Enter键之前的所有字符
String a = scan.next();//字母c
char c = a.charAt(0);//子串str,返回字符串中指定位置的字符,类似于数组的挨个查找。
int i,j,num=0;
//统计次数
for(i=0;i<s.length();i++){
if(s.charAt(i)==c){
num++;
}
}
System.out.println(num);
//倒序输出
StringBuffer str = new StringBuffer(s);
System.out.println(str.reverse());
//查询位置
String child = scan.next();
int flag=0;
int index=0;
while((index=s.indexOf(child,index))!=-1){//字符串的IndexOf()方法搜索在该字符串上是否出现了作为参数传递的字符串,s.indexOf(child,index))意为在s字符串的index位置开始查找child字符串,如果找到字符串,则返回字符的起始位置 (0表示第一个字符,1表示第二个字符依此类推)如果说没有找到则返回 -1
if(flag==0)
{
System.out.print(index);
flag=1;
}
else
{
System.out.print(" " + index);
}
index = index + child.length();
}
System.out.print("\n");
//转化大小写
char[] ch = s.toCharArray();//toCharArray是将String对象的每一个下标位的对象保存在char[]中,比如:String a = "abcd"; char[] b = a.toCharArray(); 这个b保存的信息就是['a','b','c','d']。
if(ch[0]>='a'&&ch[0]<='z')
ch[0] = (char) (ch[0] - 32);
for(i=1;i<s.length();i++){
if(ch[i-1]==' ' && ch[i]>='a'&&ch[i]<='z')
ch[i] = (char) (ch[i] - 32);
}
s = new String(ch);
System.out.println(s);
}
}