当前位置: 首页 > 知识库问答 >
问题:

如何从字符串中删除一个字符

冷浩瀚
2023-03-14

使用扫描仪,我想读取char的索引,然后将其从字符串中删除。只有一个问题:如果char在字符串中出现多次,那么。替换()将删除所有这些字符。

例如,我想从字符串“纹理文本”中获取第一个“t”的索引,然后只删除那个“t”。然后我想得到第二个't'的索引,然后删除它。

import java.util.Scanner;

class Main {
  public static void main(String[] args) {
   String text = "Texty text";
   Scanner sc = new Scanner(System.in);
   int f = 0;
   int x = 0;
   while(f<1){
   char c = sc.next().charAt(0);
    for(int i = 0; i<text.length();i++){

      if(text.charAt(i)==c){

        System.out.println(x);
        x++;
      }
      else{
        x++;
      }

    }
  }
   System.out.println(text);
  }
}

共有3个答案

韩琛
2023-03-14

尝试使用txt。子串(x,y)

x=通常为0,但x是第一个开始索引y=这是您要删除的内容,例如,为字符串的最后一个字编写以下代码:txt。子字符串(0,txt.length()-1)

夏振国
2023-03-14

可能您正在寻找以下内容:

import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        String text = "Texty text";
        String copy = text;
        Scanner sc = new Scanner(System.in);
        while (true) {
            text = copy;
            System.out.print("Enter a character from '" + text + "': ");
            char c = sc.next().charAt(0);
            for (int i = 0; i < text.length(); i++) {
                if (Character.toUpperCase(text.charAt(i)) == Character.toUpperCase(c)) {
                    System.out.println(c + " was found at " + i);
                    text = text.substring(0, i) + "%" + text.substring(i + 1);
                    System.out.println("After replacing " + c + " with % at " + i + ": " + text);
                }
            }
        }
    }
}

运行示例

Enter a character from 'Texty text': x
x was found at 2
After replacing x with % at 2: Te%ty text
x was found at 8
After replacing x with % at 8: Te%ty te%t
Enter a character from 'Texty text': t
t was found at 0
After replacing t with % at 0: %exty text
t was found at 3
After replacing t with % at 3: %ex%y text
t was found at 6
After replacing t with % at 6: %ex%y %ext
t was found at 9
After replacing t with % at 9: %ex%y %ex%
Enter a character from 'Texty text': 
魏宏邈
2023-03-14

您可以使用replaceFirst

System.out.println(text.replaceFirst("t", ""));
 类似资料:
  • 为了在Java中访问字符串的各个字符,我们有。java中是否有任何内置函数来删除字符串的单个字符? 像这样的东西:

  • 问题内容: 我想从我的字符串中删除以下所有字符 “> [],-” 目前我正在这样做。但必须有一个更有效的方法 问题答案: 使用描述要替换的所有字符的正则表达式,以及替换与该正则表达式匹配的所有内容的方法: (编辑:实际上,我认为不应该转义。而且我忘记了将反斜杠加倍,因为它们会被解释两次:一次是由Java编译器,一次是由正则表达式引擎。)

  • 问题内容: 为了访问Java中String的各个字符,我们有。是否有任何内置函数来删除Java中String的单个字符? 像这样: 问题答案: 你也可以使用可变的类。 它具有方法deleteCharAt(),以及许多其他mutator方法。 只需删除需要删除的字符,然后得到结果,如下所示: 这样可以避免创建不必要的字符串对象。

  • 问题内容: 从字符串中删除最后一个字符的最快方法是什么? 我有一个像 我想删除最后一个’,’并取回剩下的字符串: 最快的方法是什么? 问题答案: 首先,我尝试没有空格,并得到一个错误结果。 然后,我添加一个空格并获得良好的结果:

  • 如何从IronPyhon中的字符串中删除最后一个字符? 我正在寻找子字符串方法或类似的方法。

  • 问题内容: 可以说我有这个单词列表: 比我有文字 是否有匹配stopWords并在忽略大小写时将其删除的方法;像这样的地方?: 结果: 如果您了解正则表达式,效果很好,但我真的更喜欢像Commons解决方案这样的东西,它更注重性能。 顺便说一句,现在我正在使用此通用方法,该方法缺少适当的不区分大小写的处理: 问题答案: 这是不使用正则表达式的解决方案。我认为它不如我的其他答案,因为它更长且不清楚,