c語言空格分割字元串
㈠ c語言如何讀取一行數據,以空格分開
可以使用strtok函數行慶清做分割單詞。
#include<string.h>
voidmain()
{
chars[]="192.168.0.26";
char*delim=".";
char*p;
printf("%s",strtok(s,delim));
while((p=strtok(NULL,delim)))
printf("%s",p);
printf(" ");
}
(1)c語言空格分割字元串擴展閱讀
在C++中strtok的使用
#include<iostream>
#include<cstring>
usingnamespacestd;
intmain()
{
charsentence[]="Thisisasentencewith7tokens";
cout<<差枝"Thestringtobetokenizedis: "<<sentence<<" Thetokensare: ";
char*tokenPtr=strtok(sentence,"");
while(tokenPtr!=NULL){
cout<<tokenPtr<<endl;
tokenPtr=strtok(NULL,"");
}
//cout<<"Afterstrtok,sentence="<<tokenPtr<<檔前endl;
return0;
}
㈡ C語言中輸入字元串,裡面有空格,怎麼根據空格把字元串分開,並存在數組里
程序源碼如下:
#include<stdio.h>
#include<string.h>
intmain(void)
{
char str[1000];//定義一個字元串數組
char strnew[1000];//定義一個備用字元串數組
char m[]="";//定義空格變數
printf("請輸入一串字元:");//文字提示輸入字元串
gets(str);//輸入字元串
char*p=strtok(str,m);//取str與m的指針
printf("%s ",p); //輸出
p=strtok(NULL,m);
while(p) //遍歷輸出
{
printf("%s ",p); //輸出字元串
p=strtok(NULL,m); //指向下一個
}
}
程序輸出結果:
(2)c語言空格分割字元串擴展閱讀:
C語言:輸入一個字元串放入數組里,刪除其中的空格
#include <stdio.h>
#include<string.h>
#define N 100
void main()
{
int i=0,j;
char c,str[N];
printf("輸入字元串str:
");
while((c=getchar())!='
')
{
str[i]=c;//輸入字元串
i++;
}
str[i]='