[英]how to cut words and characters from a string in java
我想從字符串中刪除第一個單詞和第二個單詞的第一個字母。 有什么辦法嗎?
例如,
String a = "hello world!"
結果必須是:
“年世界!”
我嘗試使用方法子字符串,但不知道如何正確使用它。 謝謝
int index = a.indexOf(" ");
String result = index == -1 || index == a.length() - 1 ? "" : a.substring(index + 2);
String helloWorld = "Hello World!";
String newString = helloWorld.substring ( 7 , helloWorld.length ( ) );
編輯: substring
的第一個參數是您要開始的字符,例如,在"Hello World!"
W in World是第7個字符。 第二個參數是結尾的最后一個字符。 在這種情況下,只需選擇字符串的長度以最后一個字符結尾即可。
這個對我有用
String str = "hello world";
String[] strs = str.split(" ");
StringBuilder builder = new StringBuilder();
builder.append(strs[1].substring(1));
for (int i = 2; i < strs.length; i++) {
builder.append(strs[i]);
}
System.out.println(builder);
String newString = "";
String s = "I am from China!";
String[] arr = s.split(" ");
for (int i = 0; i < arr.length; i++) {
if (i == 0)
continue;
newString += arr[i] + " ";
}
newString = newString.substring(1, newString.length() - 1);
System.out.println("result:"+newString);
結果:來自中國!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.