如何使用Pascal的while do操作符去除字符串首尾空格?
嘿,我来帮你搞定用while do去除字符串首尾空格的需求,顺便把你的Pascal代码调整到位~
用While-Do实现首尾空格去除
咱们分两步实现,全程只用while do循环:
1. 清除开头空格
循环检查字符串的第一个字符是否为空格,只要是,就把字符串从第2位开始截取(相当于砍掉第一个空格),直到第一个字符不是空格为止。为了避免空字符串导致索引错误,先判断字符串长度大于0:
while (Length(t) > 0) and (t[1] = ' ') do t := Copy(t, 2, Length(t) - 1);
2. 清除结尾空格
同理,循环检查最后一个字符是否为空格,是的话就截取到倒数第2位,直到最后一个字符非空格:
while (Length(t) > 0) and (t[Length(t)] = ' ') do t := Copy(t, 1, Length(t) - 1);
整合到你的程序中
要注意:必须先去除首尾空格,再检查长度是否符合规则,不然原输入的空格会干扰长度判断。另外我还修正了原代码里的几个语法小问题(比如关键字冲突、单引号转义、缺失的if),最终代码如下:
program RandomTeksts; uses crt; var t: String; l, x, y: Integer; const tmin=1; tmax=30; label Start, EndLabel; // 注意:End是Pascal关键字,不能当标签名,改成EndLabel begin Start: clrscr; writeln('write text (from ', tmin,' to ', tmax,' chars): '); readln(t); // --- 新增:用while-do去除首尾空格 --- // 清除开头空格 while (Length(t) > 0) and (t[1] = ' ') do t := Copy(t, 2, Length(t) - 1); // 清除结尾空格 while (Length(t) > 0) and (t[Length(t)] = ' ') do t := Copy(t, 1, Length(t) - 1); // --- 去空格操作结束 --- l := Length(t); if (l < tmin) or (l > tmax) then begin writeln('Text doesn''t apply to rules!'); // 字符串内单引号需转义为两个单引号 goto EndLabel; end; clrscr; randomize; repeat x := random(52 + 1); y := random(80 + 1); textcolor(white); gotoxy(x, y); writeln(t); delay(700); clrscr; until keypressed; if ord(readkey) <> 27 then goto Start; // 补上缺失的if判断 EndLabel: end.
这样你的程序就能先处理用户输入的首尾空格,再验证长度,最后正常执行随机显示的逻辑啦~
内容的提问来源于stack exchange,提问作者Huskys




