Java 删除特定字符后的所有字符

Java 删除特定字符后的所有字符,java,Java,我有这样的话: Sams – like costco Jecy penny ? like sears 在Java中,我想将这个字符串作为: Sams  Jecy penny 是否有任何方法可以删除-和?之后的所有字符 三个选项: 使用indexOf然后使用substring 使用split,然后获取第一个返回值 使用正则表达式替换第一部分之后的所有内容 这里是拆分选项-请记住,split采用正则表达式: public class Test { public static vo

我有这样的话:

Sams – like costco
Jecy penny ? like sears
在Java中,我想将这个字符串作为:

Sams 
Jecy penny 
是否有任何方法可以删除
-
之后的所有字符

三个选项:

  • 使用
    indexOf
    然后使用
    substring
  • 使用
    split
    ,然后获取第一个返回值
  • 使用正则表达式替换第一部分之后的所有内容
这里是拆分选项-请记住,
split
采用正则表达式:

public class Test {

    public static void main(String[] args) {
        showFirstPart("Sams - like costco");
        showFirstPart("Jecy penny ? like sears");
    }

    private static void showFirstPart(String text) {
        String[] parts = text.split("[-?]", 2);
        System.out.println("First part of " + text
                           + ": " + parts[0]);
    }
}

1.
Sams-类似好市多

回答:

String s = "Sams - like costco";

String[] arr = s.split("-");

String res = arr[0];
String s = "Jecy penny ? like sears";

String[] arr = s.split("\\?");  

Added \\ before ?, as ? has a special meaning

String res = arr[0];
2.
Jecy penny?像西尔斯

回答:

String s = "Sams - like costco";

String[] arr = s.split("-");

String res = arr[0];
String s = "Jecy penny ? like sears";

String[] arr = s.split("\\?");  

Added \\ before ?, as ? has a special meaning

String res = arr[0];
尽管以上两个示例仅适用于只有一个“-”和“?”的情况,但您也可以对多个“-”和“?”进行此操作

使用
String.split()
方法

String str = "Sams – like costco";
    String str1 = "Jecy penny ? like sears";

    String[] arr = str.split("–");
    String arr1[] = str1.split("\\?");
    System.out.println(arr[0]);
    System.out.println(arr1[0]);

我假设您希望删除单词
“like”
,以及
“-”
“?”
之后的以下单词

以下是一行中的操作方法:

String output = input.replaceAll( "(?i)[-?]\\s*like\\s+\\b.+?\\b", "" );
下面是一些测试代码:

public static void main( String[] args ) {
    String input = "Sams - like costco Jecy penny ? like sears";
    String output = input.replaceAll( "(?i)[-?]\\s*like\\s+\\b.+?\\b", "" );
    System.out.println( output );
}
输出:

Sams  Jecy penny 

Jon没有工作……原因如下:String text1=“Sams Best–好市多没问题”;答案是一样的。在-我尝试字符串[]arr=text.split(“-”)之后,我无法删除;字符串res=arr[0];文本为=Sams Best–好市多可以。它不起作用是不起作用String text1=“Sams Best–好市多正常”;字符串[]arr=text1.split(“”);字符串res=arr[0];系统输出打印项次(res)===输出为Sams Best–好市多正常很抱歉给您带来不便,我之前忘记添加“\\”字符,请参见我编辑的答案…我尝试输入字符串为:Sams Best–好市多正常,但它没有工作我已检查o/p->
Sams Best
。对你有什么期望?嗯。我是不是错过了什么..String text1=“Sams Best–好市多还好”;删除(text1);函数为private static void remove(String text){String[]parts=text.split(“-”;System.out.println(parts[0]);}out为:Sams Best–costco is okUse:
private static void remove(String text){String[]parts=text.split(“-”;System.out.println(parts[0]);}
您使用的是
-
而不是
-
,这是两种不同的字符一种是使用字符串类,另一种是使用。