-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstring_walker_cli.py
More file actions
executable file
·399 lines (324 loc) · 13.2 KB
/
string_walker_cli.py
File metadata and controls
executable file
·399 lines (324 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
#!/usr/bin/env python3
"""
StringWalker CLI Application
A command-line interface for the StringWalker class that allows
interactive string navigation and manipulation.
"""
import sys
import argparse
from string_walker import StringWalker
class StringWalkerCLI:
"""Command-line interface for StringWalker."""
def __init__(self):
self.walker = None
self.running = True
def print_help(self):
"""Display help information."""
help_text = """
StringWalker CLI - Interactive String Navigation
Commands:
help, h - Show this help message
status, s - Show current status
forward <steps>, f <steps> - Walk forward by specified steps (default: 1)
backward <steps>, b <steps> - Walk backward by specified steps (default: 1)
goto <position>, g <pos> - Go to specific position
start - Go to start of string
end - Go to end of string
get <position> - Get character at specific position
replace <pos> <char> - Replace character at position
current <char> - Replace character at current position
string - Show the current string
length - Show string length
clear - Clear the screen
quit, q, exit - Exit the application
Examples:
f 3 - Walk forward 3 steps
b - Walk backward 1 step
g 5 - Go to position 5
get 7 - Get character at position 7
replace 3 X - Replace character at position 3 with 'X'
current Y - Replace current character with 'Y'
"""
print(help_text)
def print_status(self):
"""Display current status."""
if self.walker is None:
print("No string loaded. Use 'load <string>' to start.")
return
current_char = self.walker.get_current_character()
if current_char is None:
current_char = "N/A"
print(f"String: '{self.walker.get_string()}'")
print(f"Length: {self.walker.get_length()}")
print(f"Position: {self.walker.get_current_position()}")
print(f"Current character: '{current_char}'")
print(f"At start: {self.walker.is_at_start()}")
print(f"At end: {self.walker.is_at_end()}")
def load_string(self, text):
"""Load a string into the walker."""
self.walker = StringWalker(text)
print(f"Loaded string: '{text}'")
self.print_status()
def walk_forward(self, steps=1):
"""Walk forward in the string."""
if self.walker is None:
print("No string loaded.")
return
success = self.walker.walk_forward(steps)
if success:
char = self.walker.get_current_character()
print(f"Walked forward {steps} step(s) to position {self.walker.get_current_position()}: '{char}'")
else:
print(f"Cannot walk forward {steps} step(s) - would go out of bounds.")
def walk_backward(self, steps=1):
"""Walk backward in the string."""
if self.walker is None:
print("No string loaded.")
return
success = self.walker.walk_backward(steps)
if success:
char = self.walker.get_current_character()
print(f"Walked backward {steps} step(s) to position {self.walker.get_current_position()}: '{char}'")
else:
print(f"Cannot walk backward {steps} step(s) - would go out of bounds.")
def go_to_position(self, position):
"""Go to a specific position."""
if self.walker is None:
print("No string loaded.")
return
success = self.walker.go_to_position(position)
if success:
char = self.walker.get_current_character()
print(f"Went to position {position}: '{char}'")
else:
print(f"Invalid position {position}. Valid range: 0-{self.walker.get_length() - 1}")
def go_to_start(self):
"""Go to the start of the string."""
if self.walker is None:
print("No string loaded.")
return
self.walker.go_to_start()
char = self.walker.get_current_character()
print(f"Went to start (position 0): '{char}'")
def go_to_end(self):
"""Go to the end of the string."""
if self.walker is None:
print("No string loaded.")
return
self.walker.go_to_end()
char = self.walker.get_current_character()
print(f"Went to end (position {self.walker.get_current_position()}): '{char}'")
def get_character(self, position):
"""Get character at specific position."""
if self.walker is None:
print("No string loaded.")
return
char = self.walker.get_character_at(position)
if char is not None:
print(f"Character at position {position}: '{char}'")
else:
print(f"Invalid position {position}. Valid range: 0-{self.walker.get_length() - 1}")
def replace_character(self, position, new_char):
"""Replace character at specific position."""
if self.walker is None:
print("No string loaded.")
return
if len(new_char) != 1:
print("Error: New character must be exactly one character long.")
return
success = self.walker.replace_character_at(position, new_char)
if success:
print(f"Replaced character at position {position} with '{new_char}'")
print(f"Updated string: '{self.walker.get_string()}'")
else:
print(f"Failed to replace character at position {position}")
def replace_current_character(self, new_char):
"""Replace character at current position."""
if self.walker is None:
print("No string loaded.")
return
if len(new_char) != 1:
print("Error: New character must be exactly one character long.")
return
success = self.walker.replace_current_character(new_char)
if success:
print(f"Replaced current character with '{new_char}'")
print(f"Updated string: '{self.walker.get_string()}'")
else:
print("Failed to replace current character")
def show_string(self):
"""Show the current string."""
if self.walker is None:
print("No string loaded.")
return
print(f"Current string: '{self.walker.get_string()}'")
def show_length(self):
"""Show the string length."""
if self.walker is None:
print("No string loaded.")
return
print(f"String length: {self.walker.get_length()}")
def clear_screen(self):
"""Clear the screen."""
import os
os.system('cls' if os.name == 'nt' else 'clear')
def process_command(self, command):
"""Process a command line."""
parts = command.strip().lower().split()
if not parts:
return
cmd = parts[0]
try:
if cmd in ['help', 'h']:
self.print_help()
elif cmd in ['status', 's']:
self.print_status()
elif cmd in ['forward', 'f']:
steps = int(parts[1]) if len(parts) > 1 else 1
self.walk_forward(steps)
elif cmd in ['backward', 'b']:
steps = int(parts[1]) if len(parts) > 1 else 1
self.walk_backward(steps)
elif cmd in ['goto', 'g']:
if len(parts) < 2:
print("Usage: goto <position>")
return
position = int(parts[1])
self.go_to_position(position)
elif cmd == 'start':
self.go_to_start()
elif cmd == 'end':
self.go_to_end()
elif cmd == 'get':
if len(parts) < 2:
print("Usage: get <position>")
return
position = int(parts[1])
self.get_character(position)
elif cmd == 'replace':
if len(parts) < 3:
print("Usage: replace <position> <character>")
return
position = int(parts[1])
new_char = parts[2]
self.replace_character(position, new_char)
elif cmd == 'current':
if len(parts) < 2:
print("Usage: current <character>")
return
new_char = parts[1]
self.replace_current_character(new_char)
elif cmd == 'string':
self.show_string()
elif cmd == 'length':
self.show_length()
elif cmd == 'clear':
self.clear_screen()
elif cmd in ['quit', 'q', 'exit']:
print("Goodbye!")
self.running = False
else:
print(f"Unknown command: {cmd}")
print("Type 'help' for available commands.")
except (ValueError, IndexError) as e:
print(f"Error: {e}")
print("Type 'help' for command usage.")
def run_interactive(self):
"""Run the interactive CLI."""
print("StringWalker CLI - Interactive String Navigation")
print("Type 'help' for available commands.")
print("Type 'quit' to exit.")
print()
# Load initial string if provided as argument
if len(sys.argv) > 1:
initial_string = ' '.join(sys.argv[1:])
self.load_string(initial_string)
else:
# Prompt for initial string
initial_string = input("Enter a string to walk through: ").strip()
if initial_string:
self.load_string(initial_string)
else:
print("No string provided. Use 'load <string>' to start.")
print()
while self.running:
try:
command = input("walker> ").strip()
if command:
self.process_command(command)
print()
except KeyboardInterrupt:
print("\nUse 'quit' to exit.")
except EOFError:
print("\nGoodbye!")
break
def main():
"""Main entry point for the CLI application."""
parser = argparse.ArgumentParser(
description="StringWalker CLI - Interactive string navigation tool",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
Examples:
%(prog)s "Hello World" # Start with initial string
%(prog)s # Start without initial string
"""
)
parser.add_argument(
'string',
nargs='?',
help='Initial string to load (optional)'
)
parser.add_argument(
'--demo',
action='store_true',
help='Run a quick demo instead of interactive mode'
)
args = parser.parse_args()
if args.demo:
run_demo()
else:
cli = StringWalkerCLI()
cli.run_interactive()
def run_demo():
"""Run a quick demonstration of the StringWalker."""
print("=== StringWalker CLI Demo ===")
walker = StringWalker("Hello, World!")
print(f"Initial string: '{walker.get_string()}'")
print(f"Length: {walker.get_length()}")
print(f"Current position: {walker.get_current_position()}")
print(f"Current character: '{walker.get_current_character()}'")
print()
# Walk forward
print("Walking forward 3 steps...")
walker.walk_forward(3)
print(f"Position: {walker.get_current_position()}, Character: '{walker.get_current_character()}'")
print()
# Walk backward
print("Walking backward 1 step...")
walker.walk_backward(1)
print(f"Position: {walker.get_current_position()}, Character: '{walker.get_current_character()}'")
print()
# Get character at specific position
print("Getting character at position 7...")
char_at_7 = walker.get_character_at(7)
print(f"Character at position 7: '{char_at_7}'")
print()
# Replace character
print("Replacing character at position 7 with 'X'...")
walker.replace_character_at(7, 'X')
print(f"Updated string: '{walker.get_string()}'")
print()
# Go to specific position
print("Going to position 10...")
walker.go_to_position(10)
print(f"Position: {walker.get_current_position()}, Character: '{walker.get_current_character()}'")
print()
# Replace current character
print("Replacing current character with 'Y'...")
walker.replace_current_character('Y')
print(f"Updated string: '{walker.get_string()}'")
print()
print("=== Demo Complete ===")
print("Run without --demo flag for interactive mode.")
if __name__ == "__main__":
main()