text:
Given a Diagram, Find X
Find X
I was inspired by math questions in which one is asked to "Find X" for a given shape. Originally, I was just going to have the challenge be to print the x and y location of the character 'x' in a String. But I supposed that would be too simple. So I considered the context they were normally in, and decided finding the length of a Line next to the x just seemed appropriate.
Given a string input containing a Diagram of ascii 'lines' as well as a single 'x' and potentially junk characters, print the length of the only line that has an 'x' directly adjecent to it.
Examples
Input:
|
|
|x
|
|

Ouput:
5

Input:
|\
| \x
|  \
|___\

Output:
4

Input:
Diagram of a Wobbly Line:
IRRELEVANTTEXT____
____     ____/
    \___/ X ;)
      x

Output:
3

Input:
  ______________
 / ____________ \
 |/ __________ \|
 ||/ ________ \||
 |||/ ______ \|||
 ||||/      \||||
 |||||/  x  |||||
 |||||\_____/||||
 ||||\_______/|||
 |||\_________/||
 ||\___________/|
  \_____________/

Output:
5

Notes

The Valid line characters are \/_|
\ connects the top left and bottom right of itself.
/ connects the top right and bottom left of itself.
_ connects the left and right of itself
| connects the top and bottom of itself
A line will always be straight, and only consist of one of the line characters repeated n times.
The x will always be lowercase, and it will always be the only one in the diagram.
Adjecent refers to the x being exactly one character above, below, or besides.
The x will always be next to exactly one Line.
Tabs will never appear in the input.
Input and Output may be any acceptable format.
This is Code Golf, so Shortest Code Wins!
HAVE FUN. DO IT. ENJOY YOURSELF.

Reference Implementation

Nice challenge, but I think it would be better to guarantee no tabs in input. By saying they may occur, you´re effectively forcing everyone to add code to convert tab into 4 spaces, which has nothing to do with the main challenge.

Yeah, you've got a good point. I'll snip that.

You should add a testcase that has a shape similar to @ to stress-test answers.

Very clever challenge, I look forward to seeing some of the tactics used to solve it

http://tex.stackexchange.com/a/18354

JavaScript (ES6), 165, 155 bytes
EDIT: Inlined x and w, to save some more bytes.
Golfed
(assumes input is padded with spaces to make a rectangle)
t=>([k=e=o=1,v=t.search`\n`+2,-1,-v].some(h=>i=({"|":v-1,"_":1,"/":v,"\\":v})[d=t[r=l=t.search`x`+h]]),[...t].map(_=>o+=(k&=t[l-=i]==d)+(e&=t[r+=i]==d)),o)

Expanded
/*
   G(<input string,space padded>) => line length
*/
G=t=> {

    /*
     ! Note that these two are inlined, in the "golfed" version !
     "w" - line "width"
     "x" - index of "x"
    */
    x=t.search`x`;
    w=t.search`\n`+1;

    /*
    Locate the "line"
     l,r - left cursor, right cursor (for navigating along the line)
     k - left stop flag, e - right stop flag
     i - increment
     d - direction (char)
    */
    [k=e=o=1,v=w+1,-1,-w-1].some(h=>i=({"|":w,"_":1,"/":v,"\\":v})[d=t[r=l=x+h]]);

    /*
     Travel along the line axis in both directions

     Note, the stop condition should rather be: while(k|e),
     but we iterate over all the chars with map instead (as o is guaranteed to be < # chars),
     to save some space
    */
    [...t].map(_=>o+=(k&=t[l-=i]==d)+(e&=t[r+=i]==d));

    /*
      Resulting line length
    */
    return o;
};

Test
G=
t=>([k=e=o=1,v=t.search`\n`+2,-1,-v].some(h=>i=({"|":v-1,"_":1,"/":v,"\\":v})[d=t[r=l=t.search`x`+h]]),[...t].map(_=>o+=(k&=t[l-=i]==d)+(e&=t[r+=i]==d)),o);

[
G(
 "| \n" +
 "| \n" +
 "|x\n" +
 "| \n" +
 "| \n"
),

G(
"|\\   \n" +
"| \\x \n" +
"|  \\ \n" +
"|___\\\n"
),

G(
"Diagram of a Wobbly Line:\n" +
"IRRELEVANTTEXT____       \n" +
"____     ____\/           \n" +
"    \___\/ X ;)           \n" +
"      x                  \n"
),

G(
" ______________ \n"  +
"/ ____________ \\\n" +
"|/ __________ \\|\n" +
"||/ ________ \\||\n" +
"|||/ ______ \\|||\n" +
"||||/      \\||||\n" +
"|||||/  x  |||||\n"  +
"|||||\_____\/||||\n" +
"||||\_______\/|||\n" +
"|||\_________\/||\n" +
"||\___________\/|\n" +
" \_____________\/\n"
)
]

Sample output (if you run this in Google Chrome Developer Tools console)

[5, 4, 3, 5]

Python 3, 428 408 385 378 bytes
Working, but has a ton of potential to be golfed. I'm a bit rusty.
Assumes input is padded with spaces to make a rectangle.
EDIT: Thanks to @Artyer for 23 byte savings!
EDIT2: Wow I completely missed a 6 byte savings. Saved 1 more by swapping sides of an equals check.

*i,=map(list,input().split('\n'))
r=c=s=q=e=w=0
o=lambda y,x:len(i[0])>x>=0<=y<len(i)
d='\/_|'
for l in i:
 if'x'in l:r=i.index(l);c=l.index('x')
for a,b in(1,0),(0,1),(-1,0),(0,-1):
 y,x=r+a,c+b;f=o(y,x)and i[y][x]
 if f in d:s=f;w=d.index(f);q,e=y,x
k=lambda y,x,g=[1,1,0,1][w],v=[1,-1,1,0][w]:o(y,x)and s==i[y][x]and(exec('i[y][x]=0')or 1+k(y+g,x+v)+k(y-g,x-v))
print(k(q,e))

Expanded version with explanation:
inputtt='''  ______________.
 / ____________ \
 |/ __________ \|
 ||/ ________ \||
 |||/ ______ \|||
 ||||/      \||||
 |||||/  x  |||||
 |||||\_____/||||
 ||||\_______/|||
 |||\_________/||
 ||\___________/|
  \_____________/'''

# First, we get the input from STDIN and make it
# into a doubly-nested array

*input_text,=map(list,inputtt.split('\n'))

# A pretty cool Python trick to assign 0 to
# mulitple variables at once.

row=col=line_letter=line_row=line_col=line_char_index=0

# A function to check if a certian row and col is
# in bounds or not. Uses python's comparator chaining

in_bounds=lambda y,x:len(input_text[0])>x>=0<=y<len(input_text)

# A string to store all the line characters.
chars='\/_|'

# Search for the x
for line in input_text:

 # If this line contains the x...
 if'x'in line:

     # Mark the row and column
     row=input_text.index(line);col=line.index('x')

# For each direction...
for down,right in(1,0),(0,1),(-1,0),(0,-1):

 # Move in that direction
 y,x=row+down,col+right

 # If the position is in bounds, mark the char at that position
 line_found=in_bounds(y,x)and input_text[y][x]

 # If the char is a line char, set all the variables saying we found it
 if line_found in chars:
  line_letter=line_found
  line_char_index=chars.index(line_found)
  line_row,line_col=y,x

recur=lambda y,x,\
       # Find which directions we are supposed to recur in based on the line char
       g=[1,1,0,1][line_char_index],v=[1,-1,1,0][line_char_index]:\
       # If the char is in bounds and we are still on the line...
       in_bounds(y,x)and input_text[y][x]==line_letter and\
       # Set the spot to a 0, so we won't go back, increment,
       # and recur in both directions
       (exec('i[y][x]=0')or 1+recur(y+g,x+v)+recur(y-g,x-v))

# Finally, print the answer
print(recur(line_row,line_col))

I've made some golfing suggestions at http://pastebin.com/zKENQUeR. Feel free to use them if you want (Total: -18 bytes). Also, you might want to add  for syntax highlighting.

@Artyer Thank you! I was stupid to not do most of those, but I had no idea about the non-escaping backslash. I'm currently on mobile, but I'll be sure to incorporate your suggestions later!

Oh, and one more: First line to *i,=map(list,inputtt.split('\n')) (*i, makes i a list instead of a map) (-6 more bytes)

Wow... golfing in its entirety.

Lua, 480 Bytes
Lua, Being the Verbose Language it is, doesn't beat the Python Answer. But it doesn't need to.
a=...s={}for _ in a:gmatch"[^\n]*"do s[#s+1]={}for S in _:gmatch"."do if S=="x"then x=#s[#s]+1y=#s end s[#s][#s[#s]+1]=S end end c="\\/_|"X={-1,1,1,0}Y={-1,-1,0,-1}for _,d in pairs({{x-1,y},{x,y-1},{x+1,y},{x,y+1}})do K=d[2]k=d[1]h=s[K]w=h and h[k]C=w and c:find(w)if C then n=1 j=k J=K while true do j=j+X[C]J=J+Y[C]if s[J]and s[J][j]==w then n=n+1 else break end end j=k J=K while true do j=j-X[C]J=J-Y[C]if s[J]and s[J][j]==w then n=n+1 else break end end print(n)break end end

Similar to my reference implementation, but takes an actual shot at golfing, and does some things a bit more smartly than before. Still could probably be golfed a bit better though.
With comments.
a=... -- Take the input from the command line.
s={}  -- Store the string as a 2D Table, instead of a multiline string.
for _ in a:gmatch"[^\n]*"do -- For each new row.
    s[#s+1] = {}            -- Make a new sub-table. This is our line.
    for S in _:gmatch"."do  -- For every character.
        if S=="x"then x=#s[#s]+1y=#s end -- If it's an x, mark down the X and Y position of it.
        s[#s][#s[#s]+1]=S                -- Push the character. This could probably be better golfed.
    end
end
c="\\/_|"   -- The ascii line characters.
X={-1,1,1,0}    -- Their X Directionals.
Y={-1,-1,0,-1}  -- Their Y Directionals.
                -- These are inversed to get their opposite direction.
for _,d in pairs({{x-1,y},{x,y-1},{x+1,y},{x,y+1}}) do -- For each up down left and right.
    K=d[2]  -- K = y
    k=d[1]  -- k = x
    h=s[K]  -- h = the yth row
    w=h and h[k]    -- w = the xth character of the yth row, if the yth row exists.
    C=w and c:find(w) -- C = the id of the ascii line character, if w existed.
    if C then
        n=1 -- n = the length of the line.
        j=k -- Temp x
        J=K -- Temp y
        while true do
            j=j+X[C] -- Increment j by the directional of the ascii.
            J=J+Y[C] -- Ditto. for J
            if s[J]and s[J][j]==w then -- if it's still the same.
                n=n+1 -- Add 1 to the length.
            else
                break -- Or stop.
            end
        end
        j=k -- Re-assign the temps as their original.
        J=K
        while true do
            j=j-X[C] -- Search in the other direction.
            J=J-Y[C]
            if s[J]and s[J][j]==w then
                n=n+1
            else
                break
            end
        end
        print(n) -- Print the length.
        break
    end
end

JavaScript (ES6), 175
Assuming input is padded with spaces to make a rectangle.
s=>(o=>{s.replace(/[_|\\/]/g,(c,p)=>[o,-o,1,-1].map(d=>s[p+d]=='x'?[q,k]=[p,c]:c));for(n=z=k>'_'?o:k>'\\'?-1:k>'/'?o-1:o+1;s[q+=z]==k||z<0&&(n=-1,z=-z);)n++})(~s.search`
`)||n

Less golfed
s=>{
  o = ~s.search`\n`; // offset between rows (negated)
  // look for a line character near an 'x'
  s.replace(/[_|\\/]/g,
     (c,p)=> // for each line char 'c' in position 'p'
     [o,-o,1,-1].map(d=>s[p+d]=='x' // found a near 'x' ?
                        ?[q,k]=[p,c] // remember char and position
                        :c)
  );
  n=0;
  z=k>'_'?o:k>'\\'?-1:k>'/'?o-1:o+1; // offset to prev char of line
  while (s[q+=z]==k // move to left/top first
         || z<0 && (n=0,z=-z) // at left/top, go back and start counting
        )
    n++;
  return n-1;
}

Test Dots instead of spaces for clarity

f=
s=>(o=>{s.replace(/[_|\\/]/g,(c,p)=>[o,-o,1,-1].map(d=>s[p+d]=='x'?[q,k]=[p,c]:c));for(n=z=k>'_'?o:k>'\\'?-1:k>'/'?o-1:o+1;s[q+=z]==k||z<0&&(n=-1,z=-z);)n++})(~s.search`
`)||n

out=x=>O.textContent+=x

;["|.\n|.\n|x\n|.\n|.\n", "|\\...\n|.\\x.\n|..\\.\n|___\\\n"
,"Diagram of a Wobbly Line:\nIRRELEVANTTEXT...........\n____.....____/...........\n....\\___/.X.;)...........\n......x..................\n"
,"./ ____________ \\\n.|/ __________ \|\n.||/ ________ \\||\n.|||/ ______ \\|||\n.||||/      \\||||\n.|||||/  x  |||||\n.|||||\\_____/||||\n.||||\\_______/|||\n.|||\\_________/||\n.||\\___________/|\n. \\_____________/\n"].forEach(s=>out(s+f(s)+'\n\n'))


text:
Fizz Buzz for Turtles
Problem Description
Imagine you're a turtle on a grid.  You're given two numbers f and b, and you're facing east. You perform a march across the grid, counting each of the cells you encounter, according to the following rules:

By default, you write the count to the cell you're in, then walk forward.
If the count is divisible by f, you write F to the cell you're in, then turn right, then walk forward.
If the count is divisible by b, you write B to the cell you're in, then turn left, then walk forward.
If the count is divisible by both f and b, you write FB to the cell you're in, then walk forward.
If you reach a square you've already been to, you stop.

For example, following these rules using f = 3 and b = 5 will generate a pattern like this:
    F 28 29 FB  1  2  F
   26                 4
 F  B                 B  F
23                       7
22                       8
 F  B                 B  F
   19                11
    F 17 16 FB 14 13  F

The challenge
Write a program or function that accepts two numbers as input, corresponding to f and b, and produces as output the pattern for these numbers given by the rules above.
Formatting requirements:

Each cell is two characters wide
Cell contents are right aligned within these two characters
Cells on the same row are delimited by a space
The first column of cells must contain a non-empty cell
All rows must contain non-empty cells
Trailing whitespace is not required, but allowed
However, the total width of each row must not exceed 3 times the number of non-empty columns

Your code must work for provided test cases.
Standard loopholes are disallowed.
This is code golf; shortest answer in bytes wins.
Test cases
(f=3, b=5 case repeated here as a courtesy convenience).
f=3, b=5 ->
    F 28 29 FB  1  2  F
   26                 4
 F  B                 B  F
23                       7
22                       8
 F  B                 B  F
   19                11
    F 17 16 FB 14 13  F

f=4, b=10 ->
 F 25 26 27  F
23          29
22        1  2  3  F
21                 5
FB                 6
19                 7
18           B  9  F
17          11
 F 15 14 13  F

f=3, b=11 ->
 F 16 17  F
14       19
13     1  2  F
 F  B        4
   10        5
    F  8  7  F

f=5, b=9 ->
    F 41 42 43 44  1  2  3  4  F
   39                          6
   38                          7
   37                          8
 F  B                          B  F
34                               11
33                               12
32                               13
31                               14
 F 29 28  B              B 17 16  F
         26             19
          F 24 23 22 21  F

f=5, b=13 ->
    F 31 32 33 34  F
   29             36
   28        1  2  3  4  F
   27                    6
 F  B                    7
24                       8
23                       9
22              B 12 11  F
21             14
 F 19 18 17 16  F

Are we guaranteed that the input will always lead to a collision before we get to 100?

Yes.  More generally, so long as your code works for the provided test cases you're good to go.

Is there a specific place you (the turtle) starts?

@KritixiLithos No.  The left/top/right/bottom of the grid are defined by how the turtle travels, which depends on f and b.

Are f and b always integers?

@corvus_192 Yes.

Out of curiosity, is there an easy way to tell whether some pair f,b will lead to a collision? Will they all at some point?

@Dave If f=b you go on forever.  Otherwise you would always collide.  (Furthermore, unless f=b, you have at most 4fb steps before you collide with your path).

JavaScript (ES6), 230 240
(f,b)=>(d=>{for(g=[s=x=y=d];!(r=g[y]=g[y]||[])[x];d&1?d&2?y?--y:g=[,...g]:++y:d&2?x?--x:g=g.map(r=>[,...r]):++x)o=++s%f?'':(++d,'F'),s%b||(--d,o+='B'),r[x]=o||s})(0)||g.map(r=>[...r].map(c=>` ${c||' '}`.slice(-2)).join` `).join`
`

Less golfed
(f,b)=>{
  for(g=[s=x=y=d=0]; !(r = g[y]= g[y]||[])[x]; )
  {
    o=++s%f?'':(++d,'F')
    s%b||(--d,o+='B')
    r[x]=o||s,
    d&1
      ? d&2 ? y ? --y : g=[,...g] : ++y
      : d&2 ? x ? --x : g=g.map(r=>[,...r]) : ++x
  }
  return g.map(r=>[...r].map(c=>` ${c||' '}`.slice(-2)).join` `)
          .join`\n`
}

Test

F=
(f,b)=>(d=>{for(g=[s=x=y=d];!(r=g[y]=g[y]||[])[x];d&1?d&2?y?--y:g=[,...g]:++y:d&2?x?--x:g=g.map(r=>[,...r]):++x)o=++s%f?'':(++d,'F'),s%b||(--d,o+='B'),r[x]=o||s})(0)||g.map(r=>[...r].map(c=>` ${c||' '}`.slice(-2)).join` `).join`
`

function update()
{
  var i = I.value.match(/\d+/g)||[],f=+i[0],b=+i[1]
  O.textContent = (f>0 & b>0) ? F(f,b) : ''
}

update()
<input id=I value="3 5" oninput="update()">

Python 2, 379 338 326 bytes
Takes input as two numbers, separated by a comma. Eg. 4,5 or (4,5)
d=x=y=i=q=Q=e=E=0
p={}
f,b=input()
while(x,y)not in p:
 i+=1;l,r=i%b<1,i%f<1;d=(d+r-l)%4;p[x,y]=[[`i`,'F'][r],' F'[r]+'B'][l].rjust(2);q=min(q,x);Q=max(Q,x);e=min(e,y);E=max(E,y)
 if d%2:x+=(d==1)*2-1
 else:y+=(d!=2)*2-1
h,w=E-e+1,Q-q+1
A=[h*['  ']for x in' '*w]
for x,y in p:A[x-q][y-e]=p[x,y]
print'\n'.join(map(' '.join,A))

Version that works if path is longer than 99, 384 343 330 bytes
Shows 2 significant digits.
d=x=y=i=q=Q=e=E=0
p={}
f,b=input()
while(x,y)not in p:
 i+=1;l,r=i%b<1,i%f<1;d=(d+r-l)%4;p[x,y]=[[`i%100`,'F'][r],' F'[r]+'B'][l].rjust(2);q=min(q,x);Q=max(Q,x);e=min(e,y);E=max(E,y)
 if d%2:x+=(d==1)*2-1
 else:y+=(d!=2)*2-1
h,w=E-e+1,Q-q+1
A=[h*['  ']for x in' '*w]
for x,y in p:A[x-q][y-e]=p[x,y]
print'\n'.join(map(' '.join,A))

Examples:
input=(4,16)
 F 21 22 23  F
19          25
18          26
17          27
FB  1  2  3  F
15           5
14           6
13           7
 F 11 10  9  F

input=(6,7) (truncating version)
                                              F 63 64 65 66 67 FB  1  2  3  4  5  F
                               F 57 58 59 60  B                                   B  8  9 10 11  F
                              55                                                                13
                   F 51 52 53  B                                                                 B 15 16 17  F
                  49                                                                                19
                  48                                                                                20
          F 45 46  B                                                                                B 22 23  F
         43                                                                                25
         42                                                                                26
         41                                                                                27
    F 39  B                                                                                B 29  F
   37                                                                                31
   36                                                                                32
   35                                                                                33
   34                                                                                34
 F  B                                                                                B  F
31                                                                                37
30                                                                                38
29                                                                                39
28                                                                                40
27                                                                                41
FB                                                                                FB
25                                                                                43
24                                                                                44
23                                                                                45
22                                                                                46
21                                                                                47
 F  B                                                                                B  F
   18                                                                                50
   17                                                                                51
   16                                                                                52
   15                                                                                53
    F 13  B                                                                                B 55  F
         11                                                                                57
         10                                                                                58
         09                                                                                59
          F 07 06  B                                                                                B 62 61  F
                  04                                                                                64
                  03                                                                                65
                   F 01 00 99  B                                                                 B 69 68 67  F
                              97                                                                71
                               F 95 94 93 92  B                                   B 76 75 74 73  F
                                              F 89 88 87 86 85 FB 83 82 81 80 79  F

@Edit: Thanks to Jonathan Allan, Copper, and shooqie for savings me a bunch of bytes.

Heh, those N,4N patterns are pretty cool.

Good job. You can change while((x,y)not in p.keys()): to while(x,y)not in p: and for x,y in p.keys(): to for x,y in p. You can change l,r=i%b==0,i%f==0 to l,r=i%b<1,i%f<1 and d=(d+[0,1][r]-[0,1][l])%4 to d=(d+r-l)%4. You can change s=[[`i`,'F'][r],' F'[r]+'B'][l].rjust(2);p[(x,y)]=s to p[(x,y)]=[[`i`,'F'][r],' F'[r]+'B'][l].rjust(2). There may be more

You can save a byte with h*['  ']for x in range instead of ['  ']*h for x in range. Also, x+=[-1,1][d==1] can be replaced with x+=(d==1)*2-1, and y+=[1,-1][d==2] can be replaced with y+=(d!=2)*2-1. Also, is f,b=inputtt a typo?

p[(x,y)] => p[x,y] (not sure if it works in Python 2, though)

Excel VBA, 347 421 bytes
New version, to deal with the whitespace-requirements. Not having this in my first version was an oversight n my part, but this takes its toll in the bytecount... It now cuts and pastes the used range to cell A1.
Sub t(f, b)
x=70:y=70:Do:s=s+ 1
If Cells(y,x).Value<>"" Then
ActiveSheet.UsedRange.Select:Selection.Cut:Range("A1").Select:ActiveSheet.Paste:Exit Sub
End If
If s Mod f=0 Then Cells(y,x).Value="F":q=q+1
If s Mod b=0 Then Cells(y,x).Value=Cells(y,x).Value & "B":q=q+3
If Cells(y,x).Value="" Then Cells(y,x).Value=s
Select Case q Mod 4
Case 0:x=x+1
Case 1:y=y+1
Case 2:x=x-1
Case 3:y=y-1
End Select:Loop:End Sub

Here's the old version that did not move the end result to A1
Sub t(f,b)
x=70:y=70:Do:s=s+1:if Cells(y,x).Value<>"" then exit sub
If s Mod f=0 Then
Cells(y,x).Value="F":q=q+1
End If
If s Mod b=0 Then
Cells(y,x).Value=Cells(y,x).Value & "B":q=q+3
End If
If Cells(y,x).Value="" Then Cells(y,x).Value=s
Select Case q mod 4
Case 0:x=x+1
Case 1:y=y+1
Case 2:x=x-1
Case 3:y=y-1
End Select:Loop:End Sub

Starts at 70, 70 (or BR70 in Excel) and walks around it. Function is called with the f and b as parameters: Call t(4, 16)
@Neil just saved me a bunch of bytes, thanks!

If you replace q=q-1 with q=q+3 and Select Case q with Select Case q Mod 4 then you can get rid of the preceding two statements.

However, the total width of each row must not exceed 3 times the number of non-empty columns I guess this was added to avoid just setup a big grid and start somewhat the away from the border

@KarlNapf Fixed.

Excel VBA, 284 278 277 261 259  255 254 253 251 Bytes
Subroutine that takes input as values, F, B and outputs to cells on the Sheets(1) Object (which is restricted to the Sheets(1) object to save 2 Bytes)
Sub G(F,B)
Set A=Sheet1
R=99:C=R
Do
I=I+1
Y=Cells(R,C)
If Y<>""Then A.UsedRange.Cut:[A1].Select:A.Paste:End
If I Mod F=0Then Y="F":J=J+1
If I Mod B=0Then Y=Y+"B":J=J+3
Cells(R,C)=IIf(Y="",i,Y)
K=J Mod 4
If K Mod 2Then R=R-K+2 Else C=C+1-K
Loop
End Sub

Usage:
Call G(3, 4)

C, 305 Bytes
Thanks to @ceilingcat for finding a much better (and shorter) version
#define z strcpy(G[x]+y,
F(f,b){int G[99][99]={},d=3,x=49,y=x,i=1,q=0,s=99,t=0,u=s,v=0;for(;!G[x][y];i++)q=!(i%f)*2|i%b<1,q-3?q?d=q-1?z"F"),d+3&3:!z"B")-~d%4:sprintf(z""),"%d",i):z"FB"),d%2?x+=d-2:(y+=d-1),s=s>x?x:s,t=t<x?x:t,u=u>y?y:u,v=v<y?y:v;for(;v/u;u+=puts(""))for(x=s;t/x;)printf("%2s ",G[x++]+u);}

Try it online!
A slightly more indented version:
#define z strcpy(G[x][y],
char G[99][99][3];
d=3,x=49,y=49,i=1,q,s=99,t,u=99,v;

F(f,b)
{
    for(;!*G[x][y];i++)
    {
        q=(!(i%f))<<1|!(i%b);
        q==3&&z"FB");
        if(q==2)z"F"),d=(d+3)%4;
        if(q==1)z"B"),d=(d+1)%4;
        !q&&sprintf(G[x][y],"%d",i);
        if(d%2)x+=d-2;else y+=d-1;
        s=s>x?x:s;t=t<x?x:t;u=u>y?y:u;v=v<y?y:v;
    }
    for(y=u;y<=v;puts(""),y++)for(x=s;x<=t;x++)printf("%2s ",G[x][y]);
}

Here is a 364 byte version that handles numbers bigger than 100
#define g G[x][y]
#define z strcpy(g,
char G[99][99][9];d=3,x=49,y=49,i=1,q,s=99,t,u=99,v;F(f,b){for(;!*g;i++){q=(!(i%f))<<1|!(i%b);q==3&&z"FB");if(q==2)z" F"),d=(d+3)%4;if(q==1)z" B"),d=(d+1)%4;!q&&sprintf(G[x][y],"%2d",i);if(d%2)x+=d-2;else y+=d-1;s=s>x?x:s;t=t<x?x:t;u=u>y?y:u;v=v<y?y:v;}for(y=u;y<=v;puts(""),y++)for(x=s;x<=t;x++)printf("%2s ",g+strlen(g)-2);}

@ceilingcat.  Thanks for that.  You are really good at this.  I don't think I have one answer that hasn't been made shorter with your magic.

304 bytes

Perl, 275 bytes
Indentation is provided for readability and is not part of the code.
($f,$e)=@ARGV;
for($i=$x=1,$y=0;!$m{"$x,$y"};$i++){
    ($g,$m{"$x,$y"})=$i%$e&&$i%$f?($g,$i):$i%$f?($g+1,B):$i%$e?($g-1,F):($g,FB);
    ($g%=4)%2?($y+=$g-2):($x+=1-$g);
    ($a>$x?$a:$b<$x?$b:$x)=$x;
    ($c>$y?$c:$d<$y?$d:$y)=$y
}
for$k($c..$d){
    printf("%*s",1+length$i,$m{"$_,$k"})for$a..$b;
    say
}

Explanation:
The code works by keeping track of a hash of all places the turtle has been, and the appropriate value, stored in %m.  For example: in 3 5, $m{0,2} contains 2, and $m{1,-3} = 26.  It continues in this fashion until it reaches a place that has already been defined.  Additionally, it keeps track of the current boundaries of the turtle's path, using $a,$b,$c,$d as maximums and minimums.
Once it reaches a place it has already been, it prints the path using the boundaries, everything padded with spaces.
There is no limit to the size of the path, nor the size of the numbers.

PHP, 292 bytes
for($x=$y=$u=$l=0;!$q[$x][$y];$s="") {
    ++$i%$argv[1]?:$a-=1+$s="F";
    $i%$argv[2]?:$a+=1+$s.="B";
    $q[$x][$y]=$s?:$i;
    $z=[1,-2,-1,2][$a=($a+4)%4];
    $y+=$z%2;
    $x+=~-$z%2;
    $u>$y?$u=$y:$d>$y?:$d=$y;
    $l>$x?$l=$x:$r>$x?:$r=$x;
}
for(;$l++<=$r;print"\n")for($j=$u-1;$j++<=$d;)echo str_pad($q[$l-1][$j],3," ",0);

Try it online!
Indents are for clarity, not counted.
Follows much the same algorithm as the Perl answer. Track where the turtle has been in a 2D array, $a tracks where the turtle is facing, and $u, $d, $l, $r track the boundaries for printing. str_pad allows us to ensure that each entry is exactly 3 spaces wide for the print formatting.
For some reason I can't fathom, PHP doesn't mind me not initializing half the variables to 0, but screws up the formatting if I don't initialize others, even though it usually treats uninitialized variables as 0 when they're first used. Hence the $x=$y=$u=$l=0 bit.

Python 2, 267 262 258 249 245 243 bytes
f,b=input()
X=x=Y=y=i=p=0
g={}
S=sorted
while(p in g)<1:i+=1;g[p]='F'[i%f:]+'B'[i%b:]or`i`;p+=1j**(i/f-i/b);X,_,x=S([X,x,int(p.real)]);Y,_,y=S([Y,y,int(p.imag)])
j=Y
while j<=y:print' '.join(g.get(i+j*1j,'').rjust(2)for i in range(X,x+1));j+=1

Try it online!

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/

sort: votes


text:
Draw a hollow square of # with given width
I got this challenge from Codingame and am curious about better solutions than mine:
Given a width via standard input draw a hollow square of '#' in given width and length.
Example:
5 results in
#####
#   #
#   #
#   #
#####

I used python to solve this so i am particulary interested in other python code. But please feel free to post your solution in any language you want.

What if input is 0 or 1?

Related, though this might be different enough to not be a dupe.

Welcome to PPCG! For future questions, I encourage you to use the Sandbox where you can get meaningful feedback on a challenge before posting it to the main page.

@KarlNapf Run his test code and see what the result is.

@TimmyD Hardly necessary, in this case.

Partially related

Reading through the answers, I'm not convinced it's a dupe. Most of the answers here (golfing and regular languages) are roughly half the size of the answers on "Print N Squared."

Does "via standard input" in "Given a width via standard input" mean that we have to read from stdin or that we can use any of PPCG's standard input methods?

@ElPedro The post has been reopened for the past several hours.

Yes, and I left my code at work because I wrote it in my lunch break and now I have to wait until tomorrow to post by which time it may have been closed again. Just saying, if answers have already been posted and others may be working on an alternative solution is it right to close it and so waste their time? Just a question. Any opinions welcome. I'm not saying that I am right.

This is absolutely a duplicate. Solutions from the other challenge can be trivially modified to be valid and competitive here.

I've voted to close as unclear because we don't know if we have to support input values less than 2 (or maybe even less than 3).

Not convinced this is unclear, but it is a duplicate of Print N Squared

Charcoal, 6 bytes
Code:
ＮβＢββ#

Explanation:
Ｎβ        # Get input from the command line and store into β
   Ｂ      # Draw a hollow box with...
     β     #  Width β
      β    #  Height β
       #   #  Filled with the character '#'
           # Implicitly output the box

Try it online!

I was trying to figure out how to read input in Charcoal. Now I know :)

@Emigna Note that Ｎ can also be used in an expression, like int(input()) in Python. If this challenge were "draw a hollow rectangle with given width and height," the solution could be ＢＮＮ#.

Does Charcoal use a non-UTF8 charset?

That looks like 6 characters, not 6 bytes. β is in plenty of alternate 8-bit character sets, but I'm dubious about Ｎ(which is not N)

@Sparr Charcoal uses its own codepage.

That seems... silly.

@Sparr But it's legal, and used in lots of other languages, like Jelly.

MATL, 12 bytes
:G\1>&*~35*c

Try it online!
Explanation
:     % Input n implicitly. Push range [1 2 ... n]
      % STACK: [1 2 3 4 5]
G     % Push n again
      % STACK: [1 2 3 4 5], 5
\     % Modulo
      % STACK: [1 2 3 4 0]
1>    % Does each entry exceed 1?
      % STACK: [0 1 1 1 0]
&*    % Matrix with all pair-wise products
      % STACK: [0 0 0 0 0;
                0 1 1 1 0;
                0 1 1 1 0;
                0 1 1 1 0;
                0 0 0 0 0]
~     % Negate
      % STACK: [1 1 1 1 1;
                1 0 0 0 1;
                1 0 0 0 1;
                1 0 0 0 1;
                1 1 1 1 1]
35*   % Multiply by 35
      % STACK: [35 35 35 35 35;
                35  0  0  0 35;
                35  0  0  0 35;
                35  0  0  0 35;
                35 35 35 35 35]
c     % Convert to char. 0 is interpreted as space. Display implicitly
      % STACK: ['#####';
                '#   #';
                '#   #';
                '#   #';
                '#####']

Python 2, 62 54 bytes
f=lambda n:'#'*n+'\n#%s#'%(' '*(n-2))*(n-2)+'\n'+'#'*n

Returns #\n# when the input is 1
55 Bytes version that prints
def f(n):a=n-2;print'#'*n,'\n#%s#'%(' '*a)*a,'\n'+'#'*n

62 Bytes version that works for any input:
f=lambda n:'#'*n+'\n#%s#'%(' '*(n-2))*(n-2)+('\n'+'#'*n)*(n>1)

You do not have to say f= unless you use it––which you don't.

@Dopapp I know, but I think it's more fair that way (in comparison to full functions / programs)

@Rod Your choice, but we have a policy about anonymous functions that allows them.

Jolf, 8 bytes
,ajj"###
,ajj      draw a box with height (input) and width (input)
    "###  with a hash border

The right tool for the job :)

Out of curiosity, why are three # required?

@KevinCruijssen Each specify the horizontal struts, vertical struts, and corner pieces.

Java 7, 113 112 110 bytes
String c(int n){String r="";for(int i=n,j;i-->0;r+="\n")for(j=0;j<n;r+=i*j<1|n-i<2|n-j++<2?"#":" ");return r;}

1 byte saved thanks to @OlivierGrégoire;
2 bytes saved thanks to @cliffroot.
Derived solution based on my Creating a Crossed Square answer.
Try it here.

Could you shave a byte by doing the following for(int i=n,j;i-->0;r+="\n")? Since we don't care which is the bottom line or the top one, it doesn't make any sense to keep that order, right?

@OlivierGrégoire Thanks! I've also edited it in my Creating a Crossed Square answer, since there the same could be done.

COW, 426 405 348 330 bytes
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMMMmoOMMMMoOMoOMoOMoOMoOMoOMoOMoOMoO
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMMMmoOMMMMoOMoOMoOmoOoomMMM
moOMMMMOOmOomOoMoomoOmoOMOomoomOoMMMmoOMMMMOoMOoMOOmOomOomOomOoMoo
moOmoOMoomoOMMMmoOmoOMMMMOoMOoMOOmOomOomOomOoMoomoOmoOmoOmoOMOomoo
mOomOomOoMoomoOmoOMOomoomOomOomOomOoMoomoOmoOmoOMOOmOoMoomoOMOomoo

Try it online!  Change the number in the second line to any number to change the output.
The COW interpreter that I'm using here was written in Perl (and is newer than this challenge), but you can still get the same result by inputting the code here.
Explanation
; Note: [n] means "value stored in the nth block of memory".
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoO                                                  ;Stores 10 in [0].  10 is the code point for carriage return
MMMmoOMMMMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoO     ;Stores 32 in [1].  32 is the code point for whitespace
MMMmoOMMMMoOMoOMoO                                                              ;Stores 35 in [2].  35 is the code point for #
moOoom                                                                          ;Reads STDIN for an integer, and stores it in [3]
MMMmoOMMM                                                                       ;Copies [3] into [4]
MOO                                                                             ;Loop as long as [4] is non-zero
    mOomOoMoo                                                                   ;Navigate to [2] and print the character with that code point
    moOmoOMOo                                                                   ;Navigate to [4] and decrement
moo                                                                             ;End loop
mOoMMMmoOMMMMOoMOo                                                              ;Copy [3] into [4] and decrement [4] twice
MOO                                                                             ;Loop as long as [4] is non-zero
    mOomOomOomOoMoo                                                             ;Navigate to [0] and print the character with that code point
    moOmoOMoo                                                                   ;Navigate to [2] and print the character with that code point
    moOMMMmoOmoOMMMMOoMOo                                                       ;Navigate to [3] and copy it into [5], then decrement [5] twice
    MOO                                                                         ;Loop as long as [5] is non-zero
        mOomOomOomOoMoo                                                         ;Navigate to [1] and print the character with that code point
        moOmoOmoOmoOMOo                                                         ;Navigate to [5] and decrement
    moo                                                                         ;End loop
    mOomOomOoMoo                                                                ;Navigate to [2] and print the character with that code point
    moOmoOMOo                                                                   ;Navigate to [4] and decrement
moo                                                                             ;End loop
mOomOomOomOoMoo                                                                 ;Navigate to [0] and print the character with that code point
moOmoOmoO                                                                       ;Navigate to [3]
MOO                                                                             ;Loop as long as [3] is non-zero
    mOoMoo                                                                      ;Navigate to [2] and print the character with that code point
    moOMOo                                                                      ;Navigate to [3] and decrement
moo                                                                             ;End loop

PowerShell v2+, 48 47 bytes
param($n)($z='#'*$n--);,("#$(' '*--$n)#")*$n;$z

-1 byte thanks to JohnLBevan
Takes input $n, sets $z as $n hashmarks, with $n post-decremented. Encapsulates that in parens to place a copy on the pipeline. Then uses the comma operator to create an array of pre-decremented $n lines of #,spaces,#. Those are left on the pipeline. Then places $z again on the pipeline. Output via implicit Write-Output at the end introduces a newline between elements, so we get that for free.
Since the OP's code doesn't work for input n <= 1, I took that to mean we don't need to support input 1, either.
Examples
PS C:\Tools\Scripts\golfing> 2..6|%{"$_";.\draw-a-hollow-square.ps1 $_;""}
2
##
##

3
###
# #
###

4
####
#  #
#  #
####

5
#####
#   #
#   #
#   #
#####

6
######
#    #
#    #
#    #
#    #
######

You can knock another byte off: param($n)($z='#'*$n--);,("#$(' '*--$n)#")*$n;$z

@JohnLBevan Good idea with the script block. Thanks!

Python 2, 59 58 bytes
n=i=input()
while i:print'#%s#'%((' #'[i%n<2])*(n-2));i-=1

repl.it
Note: An input of 1 produces an output of ##, but a hollow square would never be produced for an input less than 3, so I guess this is fine.

JavaScript, 61 58 bytes
Saved 3 bytes thanks to @lmis!
n=>(b='#'[r='repeat'](n))+`
#${' '[r](n-=2)}#`[r](n)+`
`+b

(Doesn't handle 0 or 1)
For 13 extra bytes (at 71 bytes), you can!
n=>n?n-1?(b='#'[r='repeat'](n))+`
#${' '[r](n-=2)}#`[r](n)+`
`+b:'#':''

These solutions are fairly simple: they do a lot of storage to not repeat themselves to save a few bytes. Unminified without the variablsm it would look like:
n => // Anonymous function definition (Param `n` is the size)
    '#'.repeat(n) +      // # `n` times to form the top
    `
#${' '.repeat(n - 2)}#`  // Followed by a newline followed by a hash and `n` - 2 spaces and
                         // another hash to make one of the middle lines
    .repeat(n - 2) +     // The above middle lines repeated `n` - 2 times
    '#'.repeat(n)        // Followed by the top line again

Try it!

<input id="input" onkeydown="c();" onkeyup="c();" onchange="c();" onclick="c();" placeholder="Size">

By adding !n?'':n==1?'#':, an extra 15 bytes at the beginning of the function body, you can handle inputs 0 and 1.

n=>(b='#'[r='repeat'](n)) and then #${" "[r](n-=2)} etc. saves you 3 bytes by avoiding to repeat repeat :)

WinDbg, 206 200 182 170 bytes
.if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}

-6 bytes from removing parens from .if and using j instead of second .if
-18 bytes by using f instead of a .for to construct the strings.
-12 bytes by not NULL-terminating strings, instead passing length to da
Input is passed in through the pseudo-register $t0 (eg r $t0 = 5; {above-code}).
Explanation:
.if @$t0                                                *Verify width($t0) at least 1
{                                                       *(registers have unsigned values)
    r $t3 = 2000000;                                    *Set $t3 to address where the
                                                        *string will be constructed
    f @$t3 L@$t0 23;                                    *Put width($t0) '#' at 2000000($t3)
    f 2 * @$t3 L@$t0 20;                                *Put width($t0) ' ' at 4000000(2*$t3)
    eb 2 * @$t3 23;                                     *Put '#' on left of ' ' string
    eb 2 * @$t3 + @$t0 - 1 23;                          *Put '#' on right of ' ' string
    da @$t3 L@$t0;                                      *Print the top of the box
    j 1 < @$t0                                          *If width($t1) at least 2
    '
        .for (r $t1 = @$t0 - 2; @$t1; r $t1 = @$t1 - 1) *Loop width($t0)-2 times to...
        {
            da 2 * @$t3 L@$t0                           *...print the sides of the box
        };
        da @$t3 L@$t0                                   *Print the bottom of the box
    '
}

Sample output:
0:000> r$t0=0
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}

0:000> r$t0=1
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
Filled 0x1 bytes
Filled 0x1 bytes
02000000  "#"

0:000> r$t0=2
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
Filled 0x2 bytes
Filled 0x2 bytes
02000000  "##"
02000000  "##"

0:000> r$t0=5
0:000> .if@$t0{r$t3=2000000;f@$t3 L@$t0 23;f2*@$t3 L@$t0 20;eb2*@$t3 23;eb2*@$t3+@$t0-1 23;da@$t3 L@$t0;j1<@$t0'.for(r$t1=@$t0-2;@$t1;r$t1=@$t1-1){da2*@$t3 L@$t0};da@$t3 L@$t0'}
Filled 0x5 bytes
Filled 0x5 bytes
02000000  "#####"
04000000  "#   #"
04000000  "#   #"
04000000  "#   #"
02000000  "#####"

C, 98 bytes
f(n,i){i=n*(n+1);while(i--){putchar(i%(n+1)==n?10:i<n||i>n*n-1||i%(n+1)==0||i%(n+1)==n-1?35:32);}}

Usage:
f(5)

05AB1E, 20 bytes
'#×D¹Íð×'#.ø¹Í×sJ¹ä»

Try it online!
Or 18 bytes if we can ignore 1 <= n:
F„ #N¹<%_è¹Í×'#.ø,

Try it online!

Python 2, 47 bytes
Works for all n greater than 1.
lambda n:'#'*n+('#%*s'%(n,'#\n')*~-n)[n:]+'#'*n

Try it online!

Nice answer! This definitely qualifies for the bounty but I can't start one because the question is closed. Maybe I can post it for some other answer of yours you want highlighted and link here?

@xnor I have an answer here on a similar challenge. Perhaps you can bounty that one instead.

Ruby, 39 bytes
->n{puts a=?#*n,[?#+' '*(n-=2)+?#]*n,a}

Turns out to be shorter this way than all the fancy stuff I was trying. Be advised that this doesn't handle 0 or 1 at all.

Python 2, 50 bytes
m=input()-2
for c in'#'+' '*m+'#':print'#'+m*c+'#'

Works for n>=2. Prints each line with a pound sign, n-2 of the appropriate symbol, then another pound sign.
Aliasing the pound symbol gives same length:
m=input()-2;p='#'
for c in p+' '*m+p:print p+m*c+p

Other attempts:
lambda n:'#'*n+('\n#'+' '*(n-2)+'#')*(n-2)+'\n'+'#'*n

lambda n:'#'*n+'\n#%s#'%((n-2)*' ')*(n-2)+'\n'+'#'*n

lambda n:'\n'.join(['#'*n]+['#'+' '*(n-2)+'#']*(n-2)+['#'*n])

n=input();s='#'+' '*(n-2)+'#'
for c in s:print[s,'#'*n][c>' ']

s='##'+' #'*(input()-2)+'##'
for c in s[::2]:print s[c>' '::2]

s='#'+' '*(input()-2)+'#'
for c in s:print s.replace(' ',c)

I'm unsure whether this qualifies for your bounty, but I was able to find a lambda solution giving 47 bytes.

Haskell, 49 bytes
n%b='#':(b<$[3..n])++"#\n"
f n=(n%)=<<init(n%' ')

Works for n>=2. Defines the operation of sandwiching a character between # for an n-character newline-terminated string, then applies it twice to make a 2D grid.
Call like:
*Main> putStrLn$ f 5
#####
#   #
#   #
#   #
#####

Python, 109 bytes
n=int(input())
for x in range(n):
 r=list(' '*n);r[0]=r[-1]='#'
 if x%(n-1)==0:r='#'*n
 print("".join(r))

You can replace list(' '*n) with [' ']*n.  You can also replace x%(n-1) with x%~-n

also, if you turn the for block into a list comprehension you can save more than 20 bytes

Also, swith to Python 2, drop int() and the brackets around print.

Use <1 instead of ==0.

C, 83 82 80 78 77 Bytes
i,j;f(n){for(i=n;i--;puts(""))for(j=n;j--;putchar(i*j&&i^n-1&&j^n-1?32:35));}

Sneak in a multiply and save a byte...
i,j;f(n){for(i=n;i--;puts(""))for(j=n;j--;putchar(i&&j&&i^n-1&&j^n-1?32:35));}

Also count down j and save a few more...
i,j;f(n){for(i=n;i--;puts(""))for(j=0;j++<n;putchar(i&&j^1&&i^n-1&&j^n?32:35));}

Count down i from n to zero and save a few bytes...
i,j;f(n){for(i=0;i++<n;puts(""))for(j=0;j++<n;putchar(i^1&&j^1&&i^n&&j^n?32:35));}

A bit easier to understand and 1 byte more
i,j;f(n){for(i=0;i++<n;puts(""))for(j=0;j++<n;putchar(i==1|i==n|j==1|j==n?35:32));}

Do you need && instead of &?

Yes, it needs to be logical &.  I can use multiply but it requires too many parenthesis...

K (ngn/k), 17 bytes
{"# "x*/:x#:!x-1}

Try it online!
Or tacit, 20 bytes:
" #"@|/(+|:)\^ :':=:
"# "@&/(+|:)\=':1|=:  / similar

Try it online!

R, 68 70 bytes
Works for n > 1.  Thanks to @Billywob for a couple of bytes swapping out the array for a matrix.
cat(rbind(b<-'#',cbind(b,matrix(' ',n<-scan()-2,n),b),b,'
'),sep='')

Uses rbind and cbind to put rows and columns of #'s around an n-2 square matrix of spaces.  Newlines are bound to the rows as well.  The newline in the source is significant.  Input is from STDIN

Nice! I had no idea that a newline in a string implicitly adds \n. You could save two bytes by using matrix instead of  array though.

Groovy, 51 50 bytes
{n->a="*"*n+"\n";n-=2;print(a+"*${' '*n}*\n"*n+a)}

PHP, 81 69 bytes
for($n=-1+$i=$argv[1];$i--;)echo str_pad("#",$n," #"[$i%$n<1]),"#\n";

Run with -r; provide input as argument.
Throws a DivisionByZeroError for input=1.

Pyke, 11 bytes
ttDd*n+*.X#

Try it here!
ttDd*n+*    - a square of spaces n-2*n-2 big
        .X# - surround in `#`

Common Lisp, 150 130 bytes
-20 thanks to @Cyoce and @AlexL.
(defun s(v)(format t"~v,,,vA~%"v #\# #\#)(dotimes(h(- v 2))(format t"~v,,,vA~A~%"(- v 1)#\  #\# #\#))(format t"~v,,,vA"v #\# #\#))

Usage:
* (s 5)
#####
#   #
#   #
#   #
#####

Basically uses format twice for the top and bottom and a loop for the rows in between. The format call for the top and bottom outputs a line starting with # and padded to the appropriate width with #s. The format call for the rows in between works similarly, except the padding is spaces and a # gets printed at the end of the line.
Note: I'm rather new to Lisp and expect to have a lot of room for improvement on this.

Why not name it s? Or do am anonymous function?

I don't know Lisp, but are all of the spaces between a word and an open bracket to its right necessary? Like, does it have to be dotimes (h (- v 2)) or could it be dotimes(h(- v 2))?

@AlexL. yeah, there are a lot of opportunities for improvement here. A ton of whitespace can be removed between parentheses and other symbols. I'll just do that really quickly

Dyalog APL, 20 bytes
{' #'[1+∘.∨⍨1⍵∊⍨⍳⍵]}

Try it online!
This is an improved version on my first attempt suggested by dzaima on the APL Orchard, so all credit goes to him.
Takes an integer n as input. Using 5 as an example:
                ⍳⍵   integers from 1 to n
                      1 2 3 4 5
            1⍵∊⍨     check whether each integer is 1 or n
                      1 0 0 0 1
        ∘.∨⍨         generate all possible pairs of the
                     0s and 1s in a matrix, or'ing each pair:
                      ∨ | 1 0 0 0 1
                      --+----------
                      1 | 1 1 1 1 1
                      0 | 1 0 0 0 1
                      0 | 1 0 0 0 1
                      0 | 1 0 0 0 1
                      1 | 1 1 1 1 1
      1+             add 1 to each number
                      2 2 2 2 2
                      2 1 1 1 2
                      2 1 1 1 2
                      2 1 1 1 2
                      2 2 2 2 2
 ' #'[            ]  turn 1 into space (the first character)
                     and 2 into # (the second character)

Haskell, 67 bytes
l#n=l<$[1..n]
f n=unlines$'#'#n:('#':' '#(n-2)++"#")#(n-2)++['#'#n]

Usage example:
Prelude> putStrLn $ f 4
####
#  #
#  #
####

How it works:
l#n=l<$[1..n]                      -- helper function that makes n copies of l

   '#'#n                           -- make a string of n copies of #, followed by
                        #(n-2)     -- n-2 copies of
     '#':' '#(n-2)++"#"            -- # followed by n-2 times spaces, followed by #
                           ['#'#n] -- and a final string with n copies of #
unlines                            -- join with newlines in-between

Jelly, 13, bytes
,þ%µỊṀ€€ị⁾# Y

TryItOnline! or try 0 to 15
How?
,þ%µỊṀ€€ị⁾# Y - Main link: n
 þ            - outer product with
,             -    pair:   [[[1,1],[2,1],...,[n,1]],[[1,2],[2,2],...,[n,2]], ... ,[[1,n],[2,n],...,[n,n]]]
  %           - mod n:     [[[1,1],[2,1],...,[0,1]],[[1,2],[2,2],...,[0,2]], ... ,[[1,0],[2,0],...,[0,0]]]
   µ          - monadic chain separation
    Ị         - abs(z)<=1: [[[1,1],[0,1],...,[1,1]],[[1,0],[0,0],...,[1,0]], ... ,[[1,1],[0,1],...,[1,1]]]
      €€      - for each for each
     Ṁ        - maximum:   [[1,    1,    ...,1],    [1,    0,    ..., 1],    ... ,[1,    1,    ..., 1]   ]
        ị     - index into (1 based)
         ⁾#   - "# ":      ["##...#","# ...#", ...,"##...#"]
           Y  - join with line feeds

Racket 113 bytes
(let*((d display)(g(λ()(for((i n))(d"#")))))(g)(d"\n")(for((i(- n 2)))(d"#")(for((i(- n 2)))(d" "))(d"#\n"))(g))

Ungolfed:
(define (f n)
  (let* ((d display)
         (g (λ ()
              (for ((i n))
                (d "#"))
              (d "\n"))))
    (g)
    (for ((i (- n 2)))
      (d "#")
      (for ((i (- n 2)))
        (d " ") )
      (d "#\n"))
    (g)))

Testing:
(f 5)

Output:
#####
#   #
#   #
#   #
#####

Pip, 16 bytes
15 bytes of code, +1 for -n flag.
(Y_Xa-2WR'#s)My

Works for input >= 2. Try it online!
Explanation of somewhat ungolfed version
First, we define a function y that takes a string argument, repeats it a-2 times (where a is the first command-line input), and wraps the result in #.
Y _ X a-2 WR '#
  _              Identity function
    X a-2        String-repeated by a-2
          WR '#  Wrapped in #
Y                Yank the resulting function into y

Next, we apply this function twice--once normally, then again with map--to obtain the square as a list of strings:
y M (y s)
    (y s)  Call function y with s (preinitialized to " ") as argument
y M        Map y to each character of the resulting string

For input of 4, (y s) results in "#  #" and y M (y s) in ["####"; "#  #"; "#  #"; "####"]. This latter value is then printed, with the -n flag causing it to be newline-separated.
Golfing tricks
To get from the ungolfed to the golfed version:

Remove spaces.
Y is an operator, which means we can use it in an expression. Instead of Y... followed by (ys), we can just do (Y...s).
The problem is, we have to yank the function before we reference it again as y; so yM(Y_Xa-2WR'#s) won't work. Solution: swap the operands of the Map operator. As long as one of them is a function and the other is an iterable type, it doesn't matter what order they come in.

C#, 154 152 bytes
Golfed:
void F(int n){Console.Write($"{new string('#',n)}\n");for(int i=2;i<n;i++)Console.Write($"#{new string(' ',n-2)}#\n");Console.Write(new string('#',n));}

Ungolfed:
    void F(int n)
    {
        Console.Write($"{new string('#', n)}\n");

        for (int i = 2; i < n; i++)
            Console.Write($"#{new string(' ', n - 2)}#\n");

        Console.Write(new string('#', n));
    }

EDIT1: Loop range optimization.

SpecBAS - 57 bytes
1 INPUT n: a$="#"*n,n-=2,b$="#"+" "*n+"#"#13: ?a$'b$*n;a$

? is shorthand for PRINT, #13 is carriage return which can be tacked on to the end of a string without needing a + to join them.
The apostrophe moves print cursor down one line.

Python 2, 60 65 69 62 61 bytes
x=input();h='#';print h*x+'\n'+(h+' '*(x-2)+h+'\n')*(x-2)+h*x

My first attempt at this problem, I will golf it down hopefully.
+5 bytes I forgot to put newlines between the lines :(
+4 bytes I forgot to add 2 to the last x :(
-7 bytes If I don't subtract 2 from the input at the beginning and subtract it where it would make sense to do so, I can actually save 7 bytes :)
-1 byte Thanks to @Cyoce for helping me save 1 byte by assigning '#' to a variable (which I called h because that's what he was thinking in the comments :P)
Still 1 byte longer than before... :(

Oops. I meant '#' (I was imagining calling the variable h and my brain goofed

@Cyoce Oh. Okay, that makes sense. :) It saves one byte, but I needed to add a few bytes to compensate for an overlooked bug. But at least my code is only 61 bytes, not 62. ;)

dc, 83 bytes
?sd0[1+[#]Pdld>k]sklkx0[1+[
]P0[#]P[1+[ ]Pdld2->x]sxlxxk[#]Pdld2->r]srld2<r[
]P0lkx

This is mostly straightforward. It's kinda late so I won't write up an explanation now, but I might edit one in later.
(Note: I'm new to dc so there are probably obvious improvements to be made here.)

Python 2, 92 bytes
def f(j):r=range(j);print'\n'.join(''.join(' #'[x*y<1or max(x,y)==j-1]for y in r)for x in r)

ForceLang, 316  314 bytes
def s set
s n io.readnum()
s g goto
def w io.write "#"
s W io.writeln
if n=0
g 3
if n=1
g 4
label 0
if i=n
g 1
s i 1+i
w
g 0
label 1
s i 0
s m n+-2
W()
label a
if i=m
g b
s i 1+i
s j 0
w
label c
if j=m
g d
s j 1+j
io.write " "
g c
label d
W "#"
g a
label b
s i 0
label 2
if i=n
g 3
s i 1+i
w
g 2
label 4
w
label 3

Stuck, 29 27 Bytes
Pretty darn long for a "golfing" language, but I have forgotten how a lot of it works :P
i_2-_u'#*N+_'#' u*'#N+++u*u

Explanation:
i_2-_u                           # take input and triplicate, subtracting 2 (5 -> [3,3,5])
      '#*N+_                     # create the top and bottom rows
            '#' u*'#N+++u*       # create input - 2 copies of middle rows
                          u      # rotate left 1 to get correct order, implicit output

Lithp, 117 bytes
Line split in two for readability:
#N::((var X (repeat "#" N))(print X)(each (seq 3 N) (scope #X::((print (+ "#"
     (repeat " " (- N 2)) "#")))))(print X))

Sample usage:
% square.lithp
(
    (import "lists")
    (def s #N::((var X (repeat "#" N))(print X)(each (seq 3 N) (scope #X::((print (+ "#" (repeat " " (- N 2)) "#")))))(print X)))
    (s 10)
)

Output:
$ ./run square.lithp
##########
#        #
#        #
#        #
#        #
#        #
#        #
#        #
#        #
##########

T-SQL 351 bytes
This is so wrong... but anyway:
DECLARE @ INT=1,@n INT=10,@a VARCHAR(MAX),@b VARCHAR(MAX),@c CHAR='#',@s VARCHAR(MAX)=''WHILE @<=@n BEGIN SET @a=concat(@a,@c)SET @b=concat(@b,(SELECT CASE WHEN @=1THEN @c WHEN @=@n THEN @c ELSE' 'END))SET @=@+1 END SET @=1 WHILE @<=@n BEGIN SET @s=@s+(SELECT CASE WHEN @=1THEN @a WHEN @=@n THEN CHAR(13)+@a ELSE CHAR(13)+@b END)SET @=@+1 END PRINT @s

Ungolfed:
DECLARE     @ INT=1,
            @n INT=10,
            @a VARCHAR(MAX),
            @b VARCHAR(MAX),
            @c CHAR='#',
            @s VARCHAR(MAX)=''
WHILE @<=@n
BEGIN
    SET @a=concat(@a,@c)
    SET @b=concat(@b,(SELECT CASE WHEN @=1THEN @c WHEN @=@n THEN @c ELSE' 'END))
    SET @=@+1;
END
SET @=1
WHILE @<=@n
BEGIN
    SET @s=@s+
    (SELECT
        CASE
            WHEN @=1THEN @a
            WHEN @=@n THEN CHAR(13)+@a
            ELSE CHAR(13)+@b
        END
    )
    SET @=@+1
END
PRINT @s

BrainF***, 152 bytes
+++++[>++>+++++++<<-],[>>>+>+>+>+<<<<<<-]>>>>[-<<.>>]++++[>>>++++++++<<<-]>--<<[<<.>.>>>[>>.<<-]<<<.>->>>[<+<+>>-]<<[>>+<<-]>--<<]<<.>>>>>[<<<<.>>>>-]

Hopefully this can be golfed a bit more.
Explanation:
+++++[>++>+++++++<<-]           Initializes to [0, 10, 35]. 10 is the charcode for a newline, 35 is the charcode for '#'
,                               Gets the input (as an ASCII char, which is converted to an integer)
[>>>+>+>+>+<<<<<<-]             Copies the input to 4 different spaces
>>>>[-<<.>>]                    Prints the appropriate number of '#'
++++[>>>++++++++<<<-]           Puts 32 in the next available space (32 is the charcode of a space)
>--<<--                         Subtracts 2 from one of the input values and the value on which to loop
[
  <<.>.>>>                      Print a newline and a '#'
  [>>.<<-]                      Print n - 2 spaces
  <<<.>->>>                     Print another '#'
  [<+<+>>-]<<[>>+<<-]>--<<      Copy n to two other spaces, then copy it back
]
<<.>>>>>                        Print a newline
[<<<<.>>>>-]                    Print the appropriate number of '#'

Try it here (visualizer) or here (repl)

Charcoal, 3 bytes
ＢＮ#

Try it online!

Ruby, 66 bytes
n=gets.to_i
puts ?#*n
if n>1
puts [?#+' '*(n-2)+?#]*(n-2),?#*n end

Common Lisp, SBCL, 64 63 bytes
(format t"#~v@{#~}#
~@*~v@{~@*#~v@t#
~}~@*#~v{#~}#"(-(read)2)1)

For n=1 will give:
##
##

but I guess it's ok, since author's solution doesn't seem to work for n=1 (tested here but maybe it's because it's other Python version?)
Other than that it should work fine.
Explanation
format  ;printing function
~v@{#~} ;loop n times, where n equals current argument
        ;printing "#" - gives n "#"s
~@*     ;go back to first argument - reuse (-(read)2)
~v@t    ;add n spaces where n is current argument

05AB1E, 6 bytes
'#Ž9¦Λ

Try it online!
'#Ž9¦Λ  # full program
     Λ  # draw lines of length...
        # implicit input...
     Λ  # made from...
'#      # literal...
     Λ  # s with directions in [N, NE, E, SE, S, SW, W, NW] with indices in each character in...
  Ž9¦   # 2460
        # implicit output

Dyalog APL, 31 29 24 23 bytes
Tacit Function that takes number of lines as argument, returns hollow square
(' #'⌷⍨1∘+)¨(∘.∨⍨⍳∊1∘,)
Output (for argument 10)
    (' #'⌷⍨1∘+)¨(∘.∨⍨⍳∊1∘,) 10
##########
#        #
#        #
#        #
#        #
#        #
#        #
#        #
#        #
##########

Vyxal Rj, 15 bytes
₌Ẋ‹%ƛ1c\#*ð∨;∑²

Try it Online!
I'm actually proud of this answer, because it took a bit of thinking and effort to obtain.
Explained
₌Ẋ‹%ƛ1c\#*ð∨;∑²
₌Ẋ‹             # Push cartesian_product(range(1, input + 1), range(1, input + 1)), input - 1
   %            # modulo those
    ƛ       ;   # over each item X:
     1c         #    does X contain 1?
       \#*      #    repeat "#" that many times
          ð∨    #    and logical or with space
            ∑²  # join into a single string and format as a grid

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Operator ASCII art
Challenge
Given an ASCII operator from the list below and a number n, draw an ASCII representation of the operator using that operator as the character with the line segments of the operator having length n.
Input
An ASCII character from the list = + - x / and an integer n where n >= 1.  (I'm using x instead of * and / instead of ÷, but you could use either one, whichever is easier). For + and x, you only have to handle odd numbers to avoid issues with alignment.
Output
An ASCII drawing of the operator composed of the character with segments of length n. Horizontal portions should have spaces between the characters to offset vertical/horizontal distance differences.
Rules
This is code-golf, so shortest code in bytes wins. Standard loopholes are forbidden.
Examples
Input: + 3
  +
+ + +
  +

Input: = 4
= = = =
= = = =

Input: = 10
= = = = = = = = = =
= = = = = = = = = =

Input: - 2
- -

Input: / 10
         /
        /
       /
      /
     /
    /
   /
  /
 /
/

Input: x 7
x     x
 x   x
  x x
   x
  x x
 x   x
x     x

can you add the test case for = 10?

I assume "x" and "+" imply odd numbers? (I just saw DrMcMoylex asked nearly the same question.)

@MartinRosenau Yes, from the Input section: "For + and x, you only have to handle odd numbers to avoid issues with alignment."

Why are X and / not spaced out?

is leading whitespace allowed?

@Adám As long as the output looks correct.

@Adám Oh and to answer your first question, because they technically don't have horizontal bits that are right next to each other like =, -, and +.  I considered specifying that they be spaced similarly, but decided against it.

To clarify: if we use ÷ for the division input, the output can be a diagonal line of ÷?

@DLosc Hmm, I had not considered what the output would be for ÷.  I guess you could do what you said, since the circles in ÷ would be kinda difficult to express.

Pip, 62 59 56 bytes
55 bytes of code, +1 for -S flag.
[sXbRA_AEv-_aM,b(Y^aWR_Xb/2s)MyRVsX,b.aYaXbJsxyRL2x]@Aa

Note that this solution works with input of ÷ for division and * for multiplication, though it uses those characters to draw ASCII-art / and x, respectively. OP has clarified that this is okay. Try it online!
How?
Here's a partially spaced and commented version. Note that a and b are the command-line args, i.e. the operator and the size respectively. The -S flag controls how lists are output: it joins on newlines first, but joins any nested lists on spaces.
[                 Build a list of all possible figures:
 sXbRA_AEv-_aM,b   0 - Multiplication
 (Y^aWR_Xb/2s)My   1 - Addition
 RVsX,b.a          2 - Division
 YaXbJs            3 - Subtraction
 x                 4 - Empty
 yRL2              5 - Equals
 x                 6 - Empty
] @ Aa            Index, mod 7, with ASCII value of a

And here are the individual sections:
Multiplication
For each row in the figure, we generate a string of spaces and then replace two of them with the input character. For row i, we want to replace the spaces at index i and b-1-i; but note that the latter can use the negative index -1-i. (It's even shorter because the variable v is preinitialized to negative 1.)
sXbRA_AEv-_aM,b
            M,b  Map this function to range(b):
sXb                Space, repeated b times
     _             Function arg
      AE           (Implicitly) convert to list and append element...
        v-_        -1 minus function arg
   RA              Replace the characters at those indices...
           a       ... with input character
                 The resulting list is output with one item per line

Addition
Using the strategy from my Draw a hollow square answer, we define a function that wraps a + in b/2 copies of its argument and returns the result as a list of characters. (Integer division // isn't necessary because the string repetition operator X automatically truncates to integer.) First, we call this function on a space, giving [" ";" ";"+";" ";" "]; then, we map the same function to that result, giving [" ";" ";"+";" ";" "] on most lines but ["+";"+";"+";"+";"+"] on the center line. This nested list is then output, because of the -S flag, with spaces between all characters on a row and newlines between rows.
(Y^aWR_Xb/2s)My
                 Anonymous function:
      _Xb/2        Function arg, repeated b/2 times (implicitly rounded down)
   aWR             Wrap a in two copies of the above
  ^                Split resulting string into list of chars
 Y               Yank that function into y
(          s)    Apply function y to space
             My  Map y to that result

Division
Each row has between b-1 and 0 spaces, followed by the input character a.
RVsX,b.a
    ,b    Range(b)
  sX      Space, repeated that many times (works itemwise)
      .a  Concatenate a (itemwise)
RV        Reverse (puts the larger number of spaces at the beginning)
          Outputs newline-separated

Subtraction
Make a space-separated row of the input character. Save a copy for later.
YaXbJs
 aXb    b copies of a
    Js  Join on space
Y       Yank into y (overwrites the function from earlier, but we're done using it anyway)
        This is a string, so it just gets output

Equals
The subtraction step stored half of what we need in y--just double it.
yRL2  (Implicitly) convert y to list and repeat it twice
      Outputs newline-separated

The dummy x values are there to pad the main list so that the modular indexing gives a unique index for each input character in +-*÷=.

V, 78, 72, 71, 68, 65, 63, 62, 61 bytes
Ç=ü-/Àé X
ç^Ó/é Àä$
ç+/ÀÄM|ÀR+
ç=/Ä
ç¯/lòhYpX
çx/rxòl3Äjxlrx

Try it online!
As always, the neck-and-neck battle with 05AB1E is really fun!
Since this contains non-ASCII characters, here is a hexdump:
0000000: c73d fc2d 2fc0 e920 580a e75e d32f e920  .=.-/.. X..^./.
0000010: c0e4 240a e72b 2fc0 c44d 7cc0 522b 200a  ..$..+/..M|.R+ .
0000020: e73d 2fc4 0ae7 af2f 6cf2 6859 7058 0ae7  .=/..../l.hYpX..
0000030: 782f 7278 f26c 33c4 6a78 6c72 78         x/rx.l3.jxlrx

This does create leading spaces in the output for = and -, but this seems to be allowed. If this is not allowed, feel free to comment and I'll roll it back.
Explanation
The "global command" (e.g. ç) applies a certain set of commands to every line that matches a certain regex. The syntax is
ç<compressed regex>/<commands>

This is the easiest way of simulating a conditional/switch statement. In my original answer, I simply created the entire ASCII-art on the right-hand side for each different character we need to search for. However, a lot of these outputs require similar commands. So I combined them. The first command ('Ç') is actually the inverse of the global command, it applies the command to every line not matching the regex. So the first command is:
Ç=ü-        " On every line not containing an '=' or an '-' (e.g. inputs '/', '+', and 'x'):
    /Àé     "   Insert *n* spaces
        X   "   Delete one of them

The following command is for inputs '=' and '-'. These two are conveniently easy and similar. After this command, we need no more processing for -.
ç^Ó         " On every line that starts with non-whitespace (e.g. every line not affected by our previous command):
   /é       "   Insert one space
            "   Move back a character
      À     "   Make *n* copies
       ä$   "   Of every character on this line

From here we just do some extra commands for each individual possible input. For +:
ç+/         " On every line containing a '+':
   ÀÄ       "   Make *n* copies of this line
     M|     "   Move to the first character of the middle line
       À    "   *n* times:
        R+  "   Replace the next two characters with '+ '

The command for equals is very straightforward. We just duplicate it with Ä. For /:
ç¯          " On every line containing a '/':
  /l        "   Move one character to the right
    ò       "   Recursively:
     h      "     Move one character to the left
      Yp    "     Make a copy of this line
        X   "     Delete one character
         ò  "   End loop (implicit)

The last one is the most complicated. It is basically a port of this answer.
çx              " On every line containing a 'x':
  /rx           "   Replace the first character with an 'x'
     ò          "   Recursively:
      l         "     Move one char to the right
       3Ä       "     Make 3 copies of this line
         j      "     Move down one line
          x     "     Delete one char
           l    "     Move one char to the right
            rx  "     Replace this char with an 'x'

so is that what multiple lines are used for?

@Conorobrien Yes. The ç command (as well as search and replace, / and ?) all simulate part of vim's command line, where you have to hit enter to actually run the command

05AB1E, 81 76 74 73 70 69 68 65 64 62 60 59 57 56 bytes
Currently in war with the V answer. I'm coming for you Dr. McMoylex :p.
Also in war with the Pip answer. I'll be watching you Mr. DLosc.

Code:
Ç6&"¹s<ú.s.Bívy¹'xQiÂðñ}, ¹×S)»¹'=Qƒ= ;ƒ¹})D¦»»Rû.c"#è.V

Or in a more readable form:
  Ç6&
"¹s<ú.s.Bívy¹'xQiÂðñ},
 ¹×S)»¹'=Qƒ=
 ;ƒ¹})D¦»»Rû.c"
#è.V

Uses the CP-1252 encoding. Try it online!

Here we go again... :P

@DrMcMoylex Hahaha, good old times :).

More readable... totally...

For a given definition of "readable".

I'm coming for you, Adnan :P

@DLosc I'll be watching you closely from now on haha :p.

JavaScript (ES6), 238 225 215 202 196 bytes
(c,n)=>[...Array(i=n*(c=="="?4:c+1-1?2:c<"-"?n+n:n+1))].map(_=>--i%(n+(c=='/'|c>'w'||n))?c>'w'?i%n&&~-i%(n+2)?" ":c:c<'-'?i%(n*2)-n&&(~i&1|(n/2^i/n/2))?" ":c:c=="/"?i%n?" ":c:i%2?c:" ":`
`).join``

Could probably be golfed, but it's a start.

Python 3, 304 283 278 bytes
Simple enough, just makes a matrix of chars and applies the different operations based on which one it is. The = and - have trailing spaces if that's not too bad.
EDIT: Thanks to @Shebang and @Rod for their suggestions which ended up saving 21 bytes!
EDIT2: Thanks to @Artyer for saving 5 bytes!
t,s=input().split()
s=int(s)
r=range(s)
b=[[' ']*s for x in r]
exec(['for x in r:b[s//2][x]=b[x][s//2]=t','b=[t*s]'+'*2'*(t=='='),'for x in r:b[x][s-x-1]='+'b[x][x]='*(t=='x')+'t'][(t>'+')+(t in'x/')])
if t in'-=+':b=[[x+' 'for x in l]for l in b]
print(*map(''.join,b),sep='\n')

You can save 8 bytes by removing the if'-'==t condition line and replacing the one above it with if t in'=-':b=[[t+' ']*s]*(2*(t>'-')) (I think).

you can wrap the functions inside a list and run using exec: exec(['+ block','/ block','x block','= block','- block']['+/x=-'.find(t)]) to save ~18 bytes

Yes, trailing spaces/newlines are acceptable.

For the first line, do .split() (No args splits on whitespace). On line 6, you missed a space (b=[[x+' 'for). You can make the last line print(*map(''.join,b),sep='\n') for 1 less bytes.

Scala, 275 bytes
(i,c)=>if(c<44){val b=(" "*(i-1)+"+\n")*((i-1)/2)
b+"+ "*i+"\n"+b}else
if(c<46)"- "*i else
if(c<48)i-1 to(0,-1)map(" "*_+"/\n")mkString else
if(c<62)"= "*i+"\n"+"= "*i
else{val a=0 to i/2-1 map(x=>" "*x+"x"+" "*((i/2-x)*2-1)+"x"+" "*x+"\n")mkString;a+" "*(i/2)+"x"+a.reverse}

Usage:
val f:((Int,Char)=>String)=...
print(f(10, '/'))

Explanation:
The code tests for the ascii value of the char to choose the right way of generating the image. The ascii values of the operators in question are:
('+' -> 43), ('-' ->45), ('/' -> 47), ('=' -> 61), ('x' -> 120)
(i,c)=>                              //define a function
  if(c<44){                            //if c is a plus
    val b=(" "*(i-1)+"+\n")*((i-1)/2)    //define the top/bottom part b as (i-1)/2 times (i-1) spaces, a plus sign and a newlineine
    b+"+ "*i+"\n"+b                      //return b, i times a plus and a space, a newline and b
  }else if(c<46)                       //if c is a '-'
    "- "*i                               //return "- " repeated i times
  else if(c<48)                        //if c is a '/'
    i-1 to(0,-1)                         //create a range from i-1 to 0 in steps of -1
    map(" "*_+"/\n")                     //map each number to that number of spaces plus a "/" and a newline
    mkString                             //join them together
  else if(c<62)                        //if c is '='
    "= "*i+"\n"+"= "*i                   //return "= " repeated i times, a newline and "= " repeated i times again
  else{                                //if c if 'x'
    val a=                               //define a, which will be the top part, as...
      0 to i/2-1                         //a range from 0 to i/2-1
      map(n=>                            //map each number n to
        " "*n                              //n spaces
        +"x"                               //plus an "x"
        +" "*((i/2-n)*2-1)                 //plus ((i/2)-n)*2-1 spaces
        +"x"                               //plus an "x"
        +" "*n                             //plus n spaces
        +"\n"                              //and a newline
      )mkString;                         //join them
    a+" "*(i/2)+"x"+a.reverse          //return a, i/2 spaces, "x" and the reverse of a
  }

JavaScript (ES6), 156 bytes
(c,n)=>[...Array(n--)].map((_,i,a)=>a.map((_,j)=>({'/':a=i+j-n,x:a&&i-j,'-':a=i+i-n,'+':a&&j+j-n,'=':a+2&&a-2}[c]?' ':c)).join(c=='='|c<'/'?' ':'')).join`\n`

Where \n represents the literal newline character.

In Firefox 49, I get SyntaxError: invalid property id as it's currently written, but changing the backticks around the slash to apostrophes fixed that. (Why do you have backticks there instead of apostrophes?)

Also, the outputs for +, - and = look different than the challenge calls for: "Horizontal portions should have spaces between the characters to offset vertical/horizontal distance differences."

@ETHproductions a) typo b) sorry, I overlooked that, will fix later.

This is ridiculously short though. I hope fixing it doesn't add too many bytes.

@ETHproductions Thanks. I think this does at a cost of 19 bytes.

An cool alternate to c<'/' would be c+1-0, not that it saves any bytes...

Dyalog APL, 91 86 bytes
Needs ⎕IO←0, which is default on many systems. Takes n as left argument, and one of + - × ÷ = as right argument.
{s←⌈⍎⍕3⍵2
t←' '⍵
d←⌽∘.=⍨⍺
s∊2 6:t[d∨⌽d∧6=s]
5=s:t[↑,/2↑¨∨/¨(⌊⍺÷2)=⍳⍺ ⍺]
(2-s)(2×⍺)⍴t}

Explanation
{
    s ← ⌈ ⍎ ⍕ 3 ⍵ 2             ⍝ calculate ceil(3 f 2), where f is the given symbol
    t ← ' '⍵                    ⍝ create a string with a space before the symbol
    d ← ⌽ ∘.=⍨ ⍺                ⍝ Boolean \ diagonal
    s ∊ 2 6: t[d ∨ ⌽ d ∧ 6 = s] ⍝ if ÷ or × index t with one or both diagonals
⍝ find coordinates that are in the middle of at least one dimension
⍝ pad with zeros for spacing
⍝ use that to index into t
    5 = s: t[ ↑ ,/ 2↑¨ ∨/¨ (⌊ ⍺ ÷ 2) = ⍳ ⍺ ⍺]
⍝ - or =:
    (2 - s) (2 × ⍺) ⍴ t       ⍝ one or two rows of double-spaced symbols
}

Mathematica, 191 bytes
e=#~Mod~2==1&;StringRiffle[Normal@SparseArray[{a_,b_}/;(a+b==d+1||a==b)[e@b&&a<3,,e@b&&(a==⌈d/2⌉||b==d),,e@b&&a<2,,a+b==d+1][[Last@ToCharacterCode@#~Mod~10]]:>#,{d=#2,2d-1}," "],"
"," "]&

Anonymous function. Takes a string and a number as input, and returns a string as output. Not the shortest by far, but still fun to write.

C, 396 bytes
#define p(x) printf(x);
i,j,k,m;f(char s,int n){i=k=0;if(s==45)for(;i<n;++i)p("- ")m=n/2;if(s==43)for(;i<n;++i)for(j=0;j<=m;++j)if(i-m)p(j-m?"  ":"+\n")else{for(;k<n;++k)p("+ ")p("\n")j+=m;}if(s==61)for(;i<2;++i){for(k=0;k<n;++k)p("= ")p("\n")}j=n;if(s==47)for(;i<n;++i){--j;for(k=0;k<j;++k)p(" ")p("/\n")}if(s==120)for(;i<n;++i){k=m-abs(m-i);for(j=0;j<n-k;++j)p(j-k?" ":"x")p(i-m?"\bx\n":"\n")}}

Call with:
int main()
{
   f('x', 5);
   return 0;
}

SOML, 104 100 bytes (non-competing)
    Cd³³b»E +=?ce*d+e{t}bd*Oe{t}} ==?b*tt} -=?b*t} /=?bc*b{j:d+p}} x=?"”cb*e{jj⁴⁴d;d+++tGG;c+;}XOdoe{O

This is kind-of competing as I'm pretty sure that everything I used here has docs on github before this questions posting date but the parser doesn't have support for some functions I used so idk.

PHP, 306 292 281 282 281 275 270 bytes
$r=str_pad("",2*$n=$argv[2],($c=$argv[1])." ")."\n";if(",">$c)$r=($m=str_repeat(str_pad($c,$n," ",0)."\n",$n/2))."$r$m";if(9<$c)$r.=$r;if(w<$c)for($r=$c;$i<$n;$r[$i*(2+$n)]=$r[++$i*$n-1]=x)$r[$i*$n+$i+$n]="\n";if("/"==$c)for($r=$s="";$i++<$n;$s.=" ")$r="$s/\n$r";echo$r;

Ooh this is bulky ... needs further golfing.
I could save 4 bytes with physical linebreaks or one byte with putting "\n" into a variable.

Nice.for the "+", I think you need to match the height and not always 3. Also you should be able golf more to use if() instead of case/break;

C, 331 Bytes
i,j;f(o,n){if(47==o)for(i=n;i;puts("")){for(j=i--;j--;putchar(j?32:o)){}}
if(43==o)for(i=n;i--;puts("")){for(j=n;j--;printf(i==n/2||!j?"+ ":" ")){}}
if(45==o)for(i=n;i--;putchar(o)){}
if(61==o)for(i=3;i--;puts("")){for(j=n;j--;putchar(i&1?32:o)){}}
if(120==o)for(i=n;i;puts("")){for(j=0;j++<n;putchar(j==i||j==n-i+1?o:32)){}i--;}}

The operator is passed as ASCII code into o and the character count into n. I only added spaces between horizontally consecutive characters into the plus sign, since this was the only one where the output would have been distorted if I hadn't and in the task it only said "should". I use two nested loops counting down (except for - where I only need one line).
= Three Lines, one of them empty, straight forward
+ using printf because of the spaces
- straight forward
/ have the inner loop print at zero and start at the outer loop's counter
x have the inner loop print at the outer loop's counter and its "inverse" n-i. Still need to look at why I'am off-by-one here.
Sample call:
#include <stdio.h>
/*  =       61
    +       43
    -       45
    /       47
    Space   32
    x       120
*/
int main(int argc, char **argv){
    printf("%s\n%s\n",argv[1], argv[2]);
    f(*argv[1],strtol(argv[2],NULL,10));
}

C#, 744 Bytes
It's like 1 million characters long, I think, but I don't care, I am just so happy that I solved this...
Golfed:
string A(string s,int n){string O="";Func<string,int,string>R=(a,b)=>{return string.Join("",Enumerable.Repeat(a,b))+"\r\n";};switch(s){case"+":for(int i=0;i<n;i++){if(i==n/2){O+=R("+",n);}else{O+="+".PadLeft(n-n/2,' ').PadRight(n-n/2,' ')+"\r\n";}}return O;case"=":return R("=",n)+R("=",n);case "-":return R("-",n);case "/":for(int i=n;i>0;i--){O+="/".PadLeft(i)+"\r\n";}return O;case "x":int x=0;string[]r=new string[n];for(int i=n;i>0;i--){if(n-x-x<0){O+="x".PadLeft(x+1)+"\r\n";break;}string row=string.Join("",Enumerable.Repeat(" ",x))+"x"+string.Join("",Enumerable.Repeat(" ",n-x-x))+"x"+"\r\n";O+=row;x++;r[x]=row;if(i==n/2)break;}for(int i=r.Length-1;i>0;i--){if(string.IsNullOrEmpty(r[i]))continue;O+=r[i];}return O;default:return "";}}

Ungolfed:
public string A(string s, int n)
{
  string O = "";

  Func<string, int, string> R = (a, b) =>
  {
    return string.Join("", Enumerable.Repeat(a, b)) + "\r\n";
  };

  switch (s)
  {
    case "+":
      for (int i = 0; i < n; i++)
      {
        if (i == n / 2)
        {
          O += R("+", n);
        }
        else
        {
          O += "+".PadLeft(n - n / 2, ' ').PadRight(n - n / 2, ' ') + "\r\n";
        }
      }
      return O;
    case "=":
      return R("=", n) + R("=", n);
    case "-":
      return R("-", n);
    case "/":
      for (int i = n; i > 0; i--)
      {
        O += "/".PadLeft(i) + "\r\n";
      }
      return O;
    case "x":
      int x = 0;
      string[] r = new string[n];
      for (int i = n; i > 0; i--)
      {
        if (n - x - x < 0)
        {
          O += "x".PadLeft(x + 1) + "\r\n";
          break;
        }
        string row = string.Join("", Enumerable.Repeat(" ", x))
          + "x"
          + string.Join("", Enumerable.Repeat(" ", n - x - x)) + "x" + "\r\n";
        O += row;
        x++;
        r[x] = row;
        if (i == n / 2)
          break;
      }
      for (int i = r.Length - 1; i > 0; i--)
      {
        if (string.IsNullOrEmpty(r[i]))
          continue;
        O += r[i];
      }
      return O;
    default:
      return "";
  }
}

Testing:
+: 3, 5, 7, 9, 11
/: 7, 8, 9, 10
-: 3, 4, 5, 6
=: 3, 4, 5, 6, 7
x: 5, 7, 9, 11

Too much to paste and format here, I created a pastebin:
Pastebin

Please golf it and provide a byte count.

Lua, 402 344 312 bytes
312:
r,p,b,x=string.rep,print,' ','x'function d(s,n)h,l=(n+1)/2,s..b;e=r(l,n)if s=='-'then p(e)elseif s=='='then p(e)p(e)else for f=1,n do p(s=='/'and(r(b,n-f)..s)or s=='+'and(f~=h and r(' ',n-1)..'+'or r('+ ',n))or f<h and r(b,f-1)..x..r(b,n-2*f)..x or f>h and r(b,n-f)..x..r(b,2*f-2-n)..x or r(b,f-1)..x)end end end

344:
r,p,b,x=string.rep,print,' ','x'function d(s,n)h,l=(n+1)/2,s..b;e=r(l,n)if s=='-'then p(e)elseif s=='='then p(e)p(e)else for f=1,n do if s=='/'then p(r(b,n-f)..s)elseif s=='+'then p(f~=h and r(' ',n-1)..'+'or r('+ ',n))elseif s=='x'then p(f<h and r(b,f-1)..x..r(b,n-2*f)..x or f>h and r(b,n-f)..x..r(b,2*f-2-n)..x or r(b,f-1)..x)end end end end

402:
r,p,b,x=string.rep,print,' ','x'function d(s,n)h=(n+1)/2;if s=='-'then p(r(s..b,n))end;if s=='='then p(r(s..b,n))p(r(s..b,n))end;if s=='/'then for i=1,n do p(r(b,n-i)..s)end end;if s=='+'then for i=1,n do p(i~=h and r(' ',n-1)..'+'or r('+ ',n))end end;if s=='x'then for i=1,n do if i<h then p(r(b,i-1)..x..r(b,n-2*i)..x)elseif i>h then p(r(b,n-i)..x..r(b,-n+2*i-2)..x)else p(r(b,i-1)..x)end end end end

90 characters reduced and it's now painful to look at even when expanded. :|

"Also looks like this is an old challenge. Oops" There's nothing wrong with answering old challenges.