在Java中删除部分字符串 [英] Remove part of string in Java

查看:333
本文介绍了在Java中删除部分字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从一个字符中删除一部分字符串,即:

I want to remove a part of string from one character, that is:

源字符串:

manchester united (with nice players)

目标字符串:

manchester united


推荐答案

有多种方法可以做到这一点。如果您有要替换的字符串,则可以使用替换替换所有 <$ c $的方法c> String class。如果您要替换子字符串,可以使用 substring API获取子字符串。

There are multiple ways to do it. If you have the string which you want to replace you can use the replace or replaceAll methods of the String class. If you are looking to replace a substring you can get the substring using the substring API.

例如

String str = "manchester united (with nice players)";
System.out.println(str.replace("(with nice players)", ""));
int index = str.indexOf("(");
System.out.println(str.substring(0, index));

要替换()中的内容,您可以使用:

To replace content within "()" you can use:

int startIndex = str.indexOf("(");
int endIndex = str.indexOf(")");
String replacement = "I AM JUST A REPLACEMENT";
String toBeReplaced = str.substring(startIndex + 1, endIndex);
System.out.println(str.replace(toBeReplaced, replacement));

这篇关于在Java中删除部分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆