![](/img/trans.png)
[英]Reason for the pointer is pointing to last character of the string literal in the 2nd case
[英]Swap the 2nd character with the next-to-last
我必須將倒數第二個字母的第二個字母替換為三個以上的字母。 示例我有這個字符串:Alex僅僅是
結果應為:Aelx死了
但是我在運行程序時得到了這個:Axel` aler
這是代碼:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,n,j=0;
char text[81],cuv[44],l;
printf("Introduce-ti textul:");
gets(text);
for(i=0;i<strlen(text);i++)
{
if(text[i] != 32) {
cuv[j]=text[i];
j += 1;
} else {
n = strlen(cuv) - 1;
l= cuv[1];
cuv[1]=cuv[n-1];
cuv[n-1]=l;
printf("%s ",cuv);
strcpy(cuv,"");
j=0;
}
}
return 0;
}
首先,您不想使用gets
。 由於不安全,已將其從標准庫中刪除,請改用fgets
。 就是說,您要做的就是將輸入字符串標記為單詞,然后如果單詞大於3個字符,則將第二個和最后一個字符互換。 一種方法是:
#include <stdio.h>
#include <string.h>
#define MAXS 256
#define MAXW 64
int main (void) {
size_t len;
char str[MAXS] = {0};
char word[MAXW] = {0};
char *p = NULL;
fgets (str, MAXS, stdin); /* read input from stdin */
/* tokenize string */
for (p = strtok (str, " "); p; p = strtok (NULL, " \n"))
{
strncpy (word, p, MAXW - 1); /* copy token to word */
if ((len = strlen (word)) > 3) /* if word > 3 */
{
char tmp = word[1]; /* swap 2nd & next to last */
word[1] = word[len-2];
word[len-2] = tmp;
}
printf ("%s ", word);
}
putchar ('\n');
return 0;
}
使用/輸出
$ printf "Alex are mere\n" | ./bin/swap2nd
Aelx are mree
或者如果您想輸入文本:
$ ./bin/swap2nd
Alex are mere
Aelx are mree
使用開始/結束指針的第二種方法
您還可以通過使用起始指針 (下面的p
)和結束指針 (下面的ep
)來逐個字符串地修改字符串,每次都停止,從而可以隨時將原始字符串修改為fgets
。 端點指針指向space
, tab
或newline
,然后使用起始指針和結束指針之間的差值檢查單詞的長度,如果長度大於3個字符,則執行字符交換。 您可以瀏覽每個版本並進行比較:
#include <stdio.h>
#define MAXS 256
int main (void) {
char str[MAXS] = {0};
char *p = NULL;
char *ep = NULL;
fgets (str, MAXS, stdin); /* read input from stdin */
p = ep = str;
while (*ep) /* for each char, if a space, tab or newline */
if (*ep == ' ' || *ep == '\t' || *ep == '\n') {
if ((ep - p) > 3) { /* if length > 3 */
char tmp = *(p + 1); /* swap chars */
*(p + 1) = *(ep - 2);
*(ep - 2) = tmp;
}
p = ++ep; /* set p to next word */
}
else
++ep;
printf ("%s\n", str);
return 0;
}
使用/輸出
$ ./bin/swap2nd2
Alex are mere
Aelx are mree
您在這兩種方法之間以及從Vlad發布的方法中選擇哪種方法在很大程度上取決於口味/選擇。 所有這些都是有效的,只是完成同一件事的不同方式。 如果您有任何問題,請告訴我。
嘗試以下方法
#include <stdio.h>
int main( void )
{
char s[] = "Alex Chiurtu";
char t[sizeof( s )];
size_t i = 0, j = 0;
do
{
t[i] = s[i];
if ( s[i] != ' ' && s[i] != '\t' && s[i] != '\0' )
{
++j;
}
else if ( j != 0 )
{
if ( j > 3 )
{
char c = t[i-j + 1];
t[i-j+1] = t[i-2];
t[i-2] = c;
}
j = 0;
}
} while ( s[i++] );
puts( s );
puts( t );
return 0;
}
程序輸出為
Alex Chiurtu
Aelx Ctiurhu
考慮到功能gets
是不安全的,並且C標准不再支持該功能。
使用32
這樣的幻數也是一個壞主意。 其含義尚不清楚。
在您的程序數組中, cuv
不是零初始化的,因此以下語句
n = strlen(cuv) - 1;
導致程序的不確定行為。 每次計算字符串的長度也不是一個好主意。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.