将空格替换为随机字符串中的某些短语

时间:2014-03-09 01:55:12

标签: java android string

我想用java编写填充空白的应用程序。我有一个段落的字符串,我想在字符串中放一些空格代替一些短语。该字符串是动态字符串。我该怎么办?

这是我从api获取字符串值的方法。字符串值是动态的。

public void getText(){
    AsyncHttpClient client = new AsyncHttpClient();
    //client.get("http://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&rvsection=0&titles=Article&rvprop=content&generator=random", new AsyncHttpResponseHandler() {

    client.get("http://en.wikipedia.org/w/api.php?action=query&generator=random&prop=extracts&exchars=1000&format=json", new AsyncHttpResponseHandler() {   
        @Override
        public void onSuccess(String response) {
            Log.d("response", "response string" + response); 
            try {
                JSONObject jsonObject= new JSONObject(response);
                JSONObject queryObj= jsonObject.getJSONObject("query");
                JSONObject pagesObj= queryObj.getJSONObject("pages");
                Iterator<?> keys= pagesObj.keys();
                while( keys.hasNext() ){
                    String key = (String)keys.next();
                    JSONObject randomObj= pagesObj.getJSONObject(key);
                  //here getting dynamic random string
                    String strExtract=randomObj.getString("extract");
                    String noHTMLString = strExtract.replaceAll("\\<.*?>","");

                    setBlankInString(noHTMLString);

                    Log.d("response", "strExtract"+ noHTMLString);

                   /* if(noHTMLString.length()<300)
                    {
                        String constantStr= setConstantString();
                        txt.setText(constantStr);
                    }
                    else 
                        txt.setText(noHTMLString);*/

                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block;
                e.printStackTrace();
            }

        }
        public void setBlankInString(String str)
        {
            String fullString= str;
            //fullString value is random value
        }

1 个答案:

答案 0 :(得分:1)

这是一个非常基本的解决方案,包括在String中创建单词数组,使用随机生成的int从随机索引开始,然后用____替换四个相邻索引。你绝对可以更多地阐述它并定制它以适合你的想象,但这应该给你一个很好的起点。

public class Tester {
    public static void main(String[] args) {
        String text = "This is a random sentence. In this example, we will be replacing some of the words with blank spaces.";
        String[] array = text.split(" ");
        int randomIndex = (int)(Math.random() * ((array.length - 1) + 1));
        int minBlankSize = 1;
        int maxBlankSize = 4;
        int blankSize = minBlankSize + (int)(Math.random() * ((maxBlankSize - minBlankSize) + 1));

        for(int i = 0; i <= blankSize && randomIndex + i != array.length; i++) {
            array[randomIndex + i] = "____";
        }

        for(String word : array) {
            System.out.print(" " + word);
        }
    }
}