字符串操作java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9713205/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 06:34:40  来源:igfitidea点击:

String Manipulation java

javastring

提问by Daniel Horowitz

So I have used this site a good deal, but I can't find an answer... How can I manipulate specific chars/strings from a larger string. I'm trying to use string.substring(pos,amount) but when I try and use it in loops I get a string Index Error. for instance- How could I remove 'e' at [4] from string "abcdefg" or just capitalize "cde"? Sorry for lack of formal code in my question, it's mainly a conceptual thing. Thank you.

所以我经常使用这个网站,但我找不到答案......我如何从更大的字符串中操作特定的字符/字符串。我正在尝试使用 string.substring(pos,amount) 但是当我尝试在循环中使用它时,我得到一个字符串索引错误。例如-如何从字符串“abcdefg”中删除 [4] 处的“e”或将“cde”大写?抱歉,我的问题中缺少正式代码,这主要是概念上的问题。谢谢你。

Thanks for the suggestions I was trying to answer this question: Write a program that takes as input a string of only letters and displays the string with every third letter capitalized starting with the second letter, and all other letters lower-case.

感谢我试图回答这个问题的建议:编写一个程序,将一个仅包含字母的字符串作为输入,并以第二个字母开头的每三个字母大写,所有其他字母小写显示该字符串。

With this code:

使用此代码:

public class Test {
    public static void main(String[] arguments){
        Scanner fish = new Scanner(System.in);      
        String a = fish.nextLine();
        int len=a.length();
        for (int i = 1; i < len; i += 3){
            String z = a.substring(i, 1);
            String q = a.substring(i + 1);
            a = z.toUpperCase() + q;
        }
        System.out.println(a);
    }
}

回答by corsiKa

There is no easy way to do what you're looking for, unfortunately. Substring is not meant for replacements. For example, some languages allow you to do this:

不幸的是,没有简单的方法可以做你正在寻找的东西。子字符串不用于替换。例如,某些语言允许您这样做:

str.substring(2,3).toUpperCase();

Java doesn't work that way. If you're looking for things like that, you're going to be best off writing a small function library that takes strings and coordinates and does the work manually. It's not baked into the String class. Look at what all is already baked into the String class! It doesn't need more functionality that only a small subset of users would use.

Java 不是这样工作的。如果您正在寻找类似的东西,最好编写一个小型函数库,它接受字符串和坐标并手动完成工作。它没有融入 String 类。看看所有已经烘焙到 String 类中的东西!它不需要更多只有一小部分用户会使用的功能。

回答by Ameya

String itself is an immutable class, hence you cannot make modifications to it. When you make modifications a new object is returned back... But that is not always the best way (in terms of performance) to manipulate Strings especially when you have a large String.

String 本身是一个不可变的类,因此您不能对其进行修改。当您进行修改时,会返回一个新对象......但这并不总是(就性能而言)操作字符串的最佳方式,尤其是当您有一个大字符串时。

Java has some other classes like StringBuffer and StringBuilder which exposes many more String manipulation operations. Following is a snippet :

Java 有一些其他类,如 StringBuffer 和 StringBuilder,它们公开了更多的字符串操作操作。以下是一个片段:

`public String manipulateStr(String sourceStr) {
    StringBuffer sb = new StringBuffer(sourceStr);
    sb.delete(5,7); // Delete characters between index 5-7
    sb.insert(10, "<inserted str>"); // Insert a new String
    return sb.toString();
}`

Hope the above helps.

希望以上有帮助。

回答by Jon Egeland

replaceAll()could be a good option here, as per the Java API:

replaceAll()根据 Java API,这里可能是一个不错的选择:

Replaces each substring of this string that matches the given regular expression with the given replacement.

用给定的替换替换此字符串中与给定正则表达式匹配的每个子字符串。

This seems to do what you want, since you could do something like:

这似乎可以满足您的需求,因为您可以执行以下操作:

str.replace('e', ''); // remove 'e' from the string, or
str.replaceAll("cde", "CDE");

The problem most people have with replaceAll()is that the first parameter is not a literal String, it is regex that gets interpreted and used as a pattern to be matched against.

大多数人遇到的问题replaceAll()是第一个参数不是文字String,而是正则表达式被解释并用作要匹配的模式。

This is just a quick example, but using replace()and replaceAll()effectively does what you want. Granted it isn't by any means the most efficient or easiest to write.

这只是一个简单的例子,但使用replace()replaceAll()有效地做你想要的。当然,它绝不是最有效或最容易编写的。

回答by Jon Egeland

If you know what you want to remove, say the letter "e", but you do not where it is in the string, you can use

如果您知道要删除的内容,请说出字母“e”,但您不知道它在字符串中的位置,您可以使用

stringName.indexOf("e");

It will return an integer of the index of the first occurrence of the string "e" within stringName. You will then have to create a new string that takes in substrings of your original string. You will have to specify the beginning and end indexes for your substrings based on the the returned integer from indexOf().

它将返回 stringName 中第一次出现字符串“e”的索引的整数。然后,您必须创建一个新字符串,该字符串接收原始字符串的子字符串。您必须根据从 indexOf() 返回的整数为子字符串指定开始和结束索引。

If you are using indexOf() to find a string that is longer than one character, for example indexOf("ef"), you will also need to take into account the length of this string.

如果您使用 indexOf() 查找长度超过一个字符的字符串,例如 indexOf("ef"),您还需要考虑该字符串的长度。

回答by Penfold

How could I remove 'e' at [4] from string "abcdefg"

如何从字符串“abcdefg”中删除 [4] 处的 'e'

As Ameya already said, if you're dealing with String objects then you can't really "remove" the e, because the String is fixed. What you have to do instead is build a newString object containing all the bits except the e:

正如 Ameya 已经说过的,如果您正在处理 String 对象,那么您无法真正“删除”e,因为 String 是固定的。您必须做的是构建一个新的String 对象,其中包含除 e 之外的所有位:

String input = "abcdefg";
String output = input.substring(0, 4) + input.substring(5);
//                     "abcd"         +       "fg"

or just capitalize "cde"?

还是大写“cde”?

Again, you can take the bit before, add the upper case of "cde", and then add the rest:

同样,您可以先取一点,添加“cde”的大写字母,然后添加其余部分:

String output = input.substring(0, 2) + input.substring(2, 5).toUpperCase()
                + input.substring(5);
//            = "ab" + "CDE" + "fg"

Write a program that takes as input a string of only letters and displays the string with every third letter capitalized starting with the second letter, and all other letters lower-case.

编写一个程序,将一个仅包含字母的字符串作为输入,并显示该字符串,从第二个字母开始,每三个字母大写,其他所有字母小写。

In this case you need to loop over the characters, so it's better to use a StringBuilder rather than adding the Strings together (for performance reasons). Here's an example of adding each character one by one, and for every third character converting it to upper case:

在这种情况下,您需要遍历字符,因此最好使用 StringBuilder 而不是将字符串添加在一起(出于性能原因)。下面是一个一个一个地添加每个字符的例子,每三个字符将其转换为大写:

StringBuilder sb = new StringBuilder();
for (int i=0; i<input.length(); i++)
{
    char c = input.charAt(i);
    if (i%3 == 1) {
        c = Character.toUpperCase(c);  // every third character upper case
    }
    else {
        c = Character.toLowerCase(c);
    }
    sb.append(c);
}
String output = sb.toString(); // aBcdEfg