[英]how not to count spaces while counting the length of string in c
我正在使用以下代碼計算字符串中的空格,但我不想計算空格。
#include<stdio.h>
#include<conio.h>
void main()
{
char*ptr,str[30];
int size=0;
int word=0;
puts("enter the string");
gets(str);
fflush(stdin);
for(ptr=str;*ptr!='\0',ptr++)
{
size++;
}
printf("size of string is = %d",size);
getchar();
}
嘗試使用指針算術代替以下代碼:
while (*ptr) {
if (*ptr != ' ') {
size++;
}
}
這將循環遍歷字符,直到遇到空終止符 '\\0',並根據需要遞增。
嘗試這個
int my_strlen(char *str)
{
int i, j = 0;
while (str[i] != '\0')
{
if (str[i] != ' ')
++j;
++i;
}
return j;
}
在你的循環中:
跳過空格
計算所有其他字符
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.