1

Is there a more or less easy way (without having to implement it all by myself) to access characters in a string using a 2D array-like syntax?

For example:

"This is a string\nconsisting of\nthree lines"

Where you could access (read/write) the 'f' with something like myString[1][12] - second line, 13th row.

1
  • 2
    I understand why you edited to show valid Java syntax, but I think your original layout was easier to understand! Commented Jul 10, 2013 at 19:07

4 Answers 4

6

You can use the split() function. Assume your String is assigned to variable s, then

String[] temp = s.split("\n");

That returns an array where each array element is a string on its own new line. Then you can do

temp[1].charAt(3);

To access the 3rd letter (zero-based) of the first line (zero-based).

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

2 Comments

Nice, that is rather straightforward.
Great. Thanks, that comes pretty close to what I'd like to have.
2

You could do it like this:

String myString = "This is a string\nconsisting of\nthree lines";
String myStringArr[] = myString.split("\n");
char myChar = myStringArr[1].charAt(12);

Comments

2

To modify character at positions in a string you can use StringBuffer

StringBuffer buf = new StringBuffer("hello");
buf.insert(3, 'F');
System.out.println("" + buf.toString());
buf.deleteCharAt(3);
System.out.println("" + buf.toString());

Other than that splitting into a 2D matrix should be self implemented.

Comments

1

Briefly, no. Your only option is to create an object that wraps and interpolates over that string, and then provide a suitable accessor method e.g.

new Paragraph(myString).get(1,12);

Note that you can't use the indexed operator [number] for anything other than arrays.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.