簡體   English   中英

從字符串中刪除字符

[英]Removing characters from a string

我有一個應用程序,在其中我從URL解析.txt文件,然后將字符串吐給用戶。 我想刪除字符串的前16個字符。 我怎樣才能做到這一點?

編輯-我想從http呼叫接收的數據中刪除16個字符。

public void onClick(View src) {
        switch(src.getId()) {
        case R.id.buttonRetrieveMetar:


            InputMethodManager imm = (InputMethodManager)   
getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(EditTextAirportCode.getWindowToken(), 0);


            textDisplayMetar.setText ("");


            airportcode = EditTextAirportCode.getText().toString();
            url = urlmetar + airportcode + ".TXT";

            //Added 06-27-11 METAR code
            textDisplayMetar.setText ("");

            try {
                HttpGet httpGet = new HttpGet(url);
                HttpClient httpclient = new DefaultHttpClient();
                // Execute HTTP Get Request
                HttpResponse response = httpclient.execute(httpGet);
                content = response.getEntity().getContent();
                BufferedReader r = new BufferedReader(new     
InputStreamReader(content));
                StringBuilder total = new StringBuilder();
                String line;

                while ((line = r.readLine()) != null) {
                    total.append(line);
                } 
                textDisplayMetar.append("\n" + total + "\n");
                    } catch (Exception e) {
                //handle the exception !
            }


   break;

謝謝!

您不能修改字符串本身,但是可以很容易地創建一個子字符串:

line = line.substring(16);

substring的單參數重載將使用給定起始索引之后的整個字符串其余部分。 兩參數重載始於第一個參數指定的索引,結束於第二個參數指定的索引(不包括)。 因此,要在“跳過”前16個字符后獲得前三個字符,請使用:

line = line.substring(16, 19);

請注意,您不必分配回相同的變量-但您需要了解它不會影響您調用它的字符串對象 所以:

String original = "hello world";
String secondPart = original.substring(6);

System.out.println(original); // Still prints hello world
System.out.println(secondPart); // Prints world

編輯:如果要刪除整個文件的前16個字符,則需要:

textDisplayMetar.append("\n" + total.toString().substring(16) + "\n");

如果您希望按行進行操作,則需要:

while ((line = r.readLine()) != null) {
    total.append(line.substring(16));
}

請注意,這兩個步驟都可能需要額外的驗證-如果您對少於16個字符的字符串調用substring(16) ,則會引發異常。

嘗試這個:

String newString = oldString.substring(16);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM