3

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.

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);
    }
}
3
  • It simply takes care. You have to think about all the possibilities. Commented Mar 15, 2012 at 2:32
  • Even if it is a conceptual thing, its much easier if you post what you've coded, even if it doesn't work correctly. It helps us understand your problem more clearly, shows you're vested in the question, and makes most SO users more likely to write up a quality answer for you. Commented Mar 15, 2012 at 2:34
  • 1
    Show the code you that gives you the exception. Commented Mar 15, 2012 at 2:35

5 Answers 5

4

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.

Java has some other classes like StringBuffer and StringBuilder which exposes many more String manipulation operations. Following 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 the above helps.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

replaceAll() could be a good option here, as per the 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.

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.

Comments

0

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

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().

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.

Comments

0

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

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 new String object containing all the bits except the e:

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

or just capitalize "cde"?

Again, you can take the bit before, add the upper case of "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 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 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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.