Manipulation java string

So, I have used this site, but I cannot find the answer ... How can I manipulate certain characters / strings from a larger string. I'm trying to use string.substring (pos, amount), but when I try to use it in loops, I get an Index Error. eg. How could I remove the "e" in [4] from the string "abcdefg" or just use "cde"? Sorry for the lack of formal code in my question, this is mostly a conceptual thing. Thank.

Thanks for the suggestions I've tried to answer this question: Write a program that takes a string of letters only as input and displays a string with every third letter capitalized, starting with the second letter, and all other letters in lowercase.

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);
    }
}

      

+3


source to share


5 answers


The string itself is an immutable class, so you cannot make changes to it. When you make changes, a new object is returned ... But that's not always the best way (from a performance standpoint) to manipulate strings, especially when you have a large string.

Java has other classes such as StringBuffer and StringBuilder that provide a variety of string manipulation operations. Below is a snippet:



`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 it helps.

+4


source


There is no easy way to do what you are looking for, unfortunately. The substring is not intended to be substituted. For example, some languages ​​allow you to do this:

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

      



Java doesn't work this way. If you're looking for this kind of thing, you'd be better off writing a small library of functions that takes strings and coordinates and does the job manually. It is not baked into a String class. See that everything is already baked into the String class! It doesn't need additional functionality that only a small subset of users will use.

0


source


replaceAll()

might be a good option here, according to the Java API:

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

This is similar to what you want, as you can 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 a regular expression that is interpreted and used as a pattern to be matched.

This is just a quick example, but using replace()

and replaceAll()

effectively does what you want. Of course, this is by no means the most efficient or simple recording.

0


source


If you know what you want to remove, say the letter "e" but you are not where it is on the line, you can use

stringName.indexOf("e");

      

It will return the integer index of the first occurrence of the string "e" in stringName. Then you will need to create a new string that accepts substrings of the original string. You will need to specify the starting and ending indices for your substrings based on the returned integer from indexOf ().

If you use indexOf () to find a string that is longer than one character, for example indexOf ("ef"), you also need to factor in the length of that string.

0


source


How can I remove the 'e' in [4] from the string "abcdefg"

As Ameya already said, if you are dealing with string objects, you cannot "delete" e, because String is fixed. Instead, you must create a new String object containing all the bits except e:

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

      

or just capital letters "cde"?

Again, you can take a bit earlier, add the uppercase "cde" and then add the rest:

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

      

Write a program that accepts a string of only letters as input and displays a string with every third letter, a capital letter starting with the second letter, and all other letters in lowercase.

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

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

      

0


source







All Articles