Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

My solution to question 1-3 #3

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 43 additions & 2 deletions src/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ with a buffer (similar to how a resizable ArrayList, and/or a
*/


import java.nio.BufferOverflowException;
import java.util.Arrays;

public class Main {
Expand All @@ -48,7 +49,7 @@ public static void main(String[] args) {
int size = 0;

// initialize the buffer and size variables with some data
String temp = "Dr Martin Luther King";
String temp = " Dr Martin Luther King ";
for (int i = 0; i < temp.length(); i++) {
buffer[i] = temp.charAt(i);
}
Expand All @@ -59,14 +60,54 @@ public static void main(String[] args) {
System.out.println("size: " + size);

// call your method here
size = modifyCStr(buffer, size);

// check the "after" buffer contents via println
// check to see if the new buffer's size is correct
System.out.println(Arrays.toString(buffer));

// check to see if the new buffer's size is correct
System.out.println("size: " + size);

}

// write your method here

/**
*
* @param buf char string
* @param size the size of the string
* @return the new size of the string
*/
public static int modifyCStr(char[] buf, int size) {
for (int i = size; i >= 0; i--) {
switch(buf[i]) {
case ' ':
// increase string size
size += 2;

// do not try if too big
if (size >= BUFFER_CAPACITY) throw new BufferOverflowException();

// shift all to right of index right by 2
for (int j = size -1; j >= i + 2 ; j--) {
// a,_,b,c,\0,\0
// will become
// a,_,b,c,b,c
buf[j] = buf[j-2];
}

// set the character to the new values
// array will become
// a,%,2,0,b,c
buf[i] = '%';
buf[i+1] = '2';
buf[i+2] = '0';


break;
}
}
return size;
}

}