-1

I have two strings: stringOne and stringTwo.

String stringOne = "JAVA";
String stringTwo = "DJDFKWAUERHFGJAVAORKFLASOWE";

I can easily locate if Java is in the second string (it is), where how would I index where it begins and ends? I want to initialize the beginning and end positions in integer variables: begPos = 14 and endPos = 18. What method would I use to do this?

Somewhat the reverse of this, but I also have a third string:

String stringThree = "                          ";

It's a bunch of whitespace. I want to put "JAVA" in there according to the positions gained before. I can replace parts of a string with other parts of a string, but again I'm not sure how to replace a specific position. The end result should be:

String stringThree = "              JAVA      ";

Any ideas?

2

4 Answers 4

3

You're looking for the indexOf() method.

3
String stringOne = "JAVA";
String stringTwo = "DJDFKWAUERHFGJAVAORKFLASOWE";
int begin=stringTwo.indexOf(stringOne);
int end=begin+stringOne.length();
if(begin==-1){
    //not found
}
1

You could use str.indexOf(substr) which returns the index of a substring into str, and the str.substring(start, end) methods:

public String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. The substring begins at the specified beginIndex and extends to the character at index endIndex - 1. Thus the length of the substring is endIndex-beginIndex.

Code:

public static void main(String[] args)
{
    String stringOne = "JAVA";
    String stringTwo = "DJDFKWAUERHFGJAVAORKFLASOWE";

    int begPos = stringTwo.indexOf(stringOne);
    int endPos = begPos + stringOne.length();

    System.out.println(begPos + " " + endPos);

    String stringThree = "......................";
    stringThree = stringThree.substring(0, begPos) + stringOne + stringThree.substring(endPos);

    System.out.println(stringThree);
}

You would like to manipulate the start and end arguments passed to substring(start, end) in order to get the expected output.

1

If you want to modify the string, use StringBuilder.

String str = "                            ";
String ins = "JAVA";
StringBuilder builder = new StringBuilder(str);
String result = builder.replace(14, 18, ins).toString();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.