软件测试 第二次作业

本文介绍两个实用的字符串处理程序:一是颠倒输入英文句子中单词的顺序;二是统计并输出给定字符串中各单词出现的频率。

一:把一个英语句子中的单词次序颠倒后输出。例如输入“how are you”,输出“you are how”

#include<stdio.h>

int main()
  {
    char sentence[100];
    int len=0,j,wordlen=0;
    gets(sentence);
      while(sentence[len]) len++;
          for(j=len-1;j>=0;j--)
        {
            if(sentence[j]>='a'&&sentence[j]<='z'||sentence[j]>='A'&&sentence[j]<='Z')
         {
                      wordlen++;
         }
         else if(wordlen>0)
            {
                printf("%*.*s",wordlen,wordlen,&sentence[j+1]);
                printf("%c",sentence[j]);
                wordlen=0;
            }
          else
            printf("%c",sentence[j]);
            }
          if(wordlen>0) printf("%*.*s",wordlen,wordlen,sentence);
          return 0;
      }

 

二:写一个程序,用于分析一个字符串中各个单词出现的频率,并将单词和它出现的频率输出显示。

package test;

import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

import java.util.Map.Entry;

 

public class wj {

  public static void main(String[] args) {

            String str = "Hello World My First Unit Test";

            String[] items = str.split(" ");

            Map<String, Integer> map = new HashMap<String, Integer>();

            for (String s : items) {

                     if (map.containsKey(s))

                              map.put(s, map.get(s) + 1);

                     else {

                              map.put(s, 1);

                     }

            }

            List<Entry<String, Integer>> list = new ArrayList<Entry<String, Integer>>();

            for (Entry<String, Integer> entry : map.entrySet()) {

                     list.add(entry);

            }

            Collections.sort(list, new EntryComparator());

 

            for (Entry<String, Integer> obj : list) {

                     System.out.println(obj.getKey() + "\t" + obj.getValue());

            }

  }

}

 

class EntryComparator implements Comparator<Entry<String, Integer>> {

  public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {

            return o1.getValue() > o2.getValue() ? 0 : 1;

  }

}

转载于:https://www.cnblogs.com/WJ-Mark/p/5375246.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值