Removing characters from a string
I have an app in which I parse a .txt file from a URL and spit out the string to the user. I want to remove the first 16 characters of the string. How can I do this?
EDIT- I want to remove 16 characters from the data I receive from my http call.
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";
开发者_JAVA百科 //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;
Thanks!
You can't modify the string itself, but you can create a substring easily enough:
line = line.substring(16);
The single-parameter overload of substring
takes the whole of the rest of the string after the given start index. The two-parameter overload starts at an index specified by the first argument, and ends at an index specified by the second argument (exclusive). So to get the first three characters after "skipping" the first 16, you'd use:
line = line.substring(16, 19);
Note that you don't have to assign back to the same variable - but you need to understand that it doesn't affect the string object that you call it on. So:
String original = "hello world";
String secondPart = original.substring(6);
System.out.println(original); // Still prints hello world
System.out.println(secondPart); // Prints world
EDIT: If you want to remove the first 16 characters of the whole file, you want:
textDisplayMetar.append("\n" + total.toString().substring(16) + "\n");
If you want that on a per-line basis, you want:
while ((line = r.readLine()) != null) {
total.append(line.substring(16));
}
Note that both of these may require extra validation - if you call substring(16)
on a string with less than 16 characters, it will throw an exception.
Try this:
String newString = oldString.substring(16);
精彩评论