删除字符串处某个位置的字符

时间:2013-12-03 14:49:16

标签: java android string

我想删除字符串特定位置的某些字符。我有这些职位,但我在删除角色方面遇到了问题。

我正在做的是:

if (string.subSequence(k, k + 4).equals("\n\t\t\t")){
    string = string.subSequence(0, k) + "" + s.subSequence(k, s.length());
}

我需要从字符串

中删除"\n\t\t\t"

6 个答案:

答案 0 :(得分:9)

使用StringBuilder

StringBuilder sb = new StringBuilder(str);

sb.delete(start, end);
sb.deleteCharAt(index);

String result = sb.toString();

答案 1 :(得分:1)

使用StringBuilder

String str="    ab a acd";
        StringBuilder sb = new StringBuilder(str);

        sb.delete(0,3);
        sb.deleteCharAt(0);

        String result = sb.toString();
        System.out.println(result);

答案 2 :(得分:1)

public static String remove(int postion, String stringName) {
    char [] charArray = stringName.toCharArray();
    char [] resultArray = new char[charArray.length];
    int count = 0;
    for (int i=0; i< charArray.length; i++) {
        if (i != postion-1) {
            resultArray[count] = charArray[i];
            count++;
        }
    }
    return String.valueOf(resultArray);
}

答案 3 :(得分:0)

使用String.ReplaceAll()代替此。

但如果您只想删除特定元素,则可以使用substring()。 现在你想知道你已经知道的位置。

答案 4 :(得分:0)

将您的积分放在名为set

的HashSet中
StringBuilder sb=new StringBuilder();
for(int i=0;i<string.length();i++){
       if(!set.contains(string.charAt(i)))
           sb.append(string.charAt(i));  
 }

 String reformattedString=sb.toString();

答案 5 :(得分:0)

首先你必须将\放在特殊字符的前面以便匹配两个字符串,因此你将拥有.equals("\"\\n\\t\\t\\t\""),否则子字符串将不会在内部被识别字符串。然后你必须解决的另一件事是索引开始和结束在.subSequence(k,k+10)内的位置,因为第一个和最后一个字符分开10个位置而不是4个。还要注意当你修补字符串时你来自将0定位到k,将k+10定位到str.length()。如果你从0 --> k and k --> length()开始,你只需加入旧字符串:)。 你的代码应该像这样工作,我已经测试过了

   if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
        {
     newstr = str.substring(0,k)+str.substring(k+10,(str.length()));
         }

您也不需要+" "+,因为您要添加字符串。想要看到这种效果的人可以运行这个简单的代码:

public class ReplaceChars_20354310_part2 {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {


    String str = "This is a weird string containg balndbfhr frfrf br brbfbrf b\"\\n\\t\\t\\t\"";

    System.out.println(str); //print str 

    System.out.println(ReplaceChars(str));  //then print after you replace the substring 

    System.out.println("\n");  //skip line 


    String str2 = "Whatever\"\\n\\t\\t\\t\"you want to put here"; //print str 

    System.out.println(str2);  //then print after you replace the substring

    System.out.println(ReplaceChars(str2));

}


      //Method ReplaceChars

       public static String ReplaceChars (String str) {

       String newstr ="";

       int k;

        k = str.indexOf("\"\\n\\t\\t\\t\""); //position were the string    starts within the larger string

      if(str.substring(k, k+10).equals("\"\\n\\t\\t\\t\""))
        {

       newstr = str.substring(0,k)+str.substring(k+10,(str.length())); //or just str

        }


           return newstr;

        }//end method


     }
相关问题