0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

C言語文字列関数

0
Posted at

文字列処理関数

C言語のstdlib.hには文字列を処理する関数が豊富に含まれています。今回の記事でいくつかの典型的な関数を紹介するとともに、これらの関数を自作する方法も紹介する。

atoi関数

使い方

atoi関数(atoi stands for ASCII to integer.)は、文字列を数値に変換した結果を変数に代入する関数です。使い方は以下:

変数 = atoi(文字列配列名);

ただし、変換のターゲットとなる文字列が非数字文字(数字文字とは0123456789の10個の文字、非数字文字はそれ以外)を含むかどうかによって、関数の動きが変わってくる。具体的には:

文字列の内容 変換結果
数字文字しか含まれない そのまま数字文字を変換 atoi("1234") = 1234
先頭は数字文字、途中で非数字文字 最初の非数字文字までの数字文字を変換 atoi("12c4") = 12
先頭は非数字文字 変換結果は0 atoi("a234") = 0

使用例:

#include <stdio.h>
#include <stdlib.h>

int main(void)
{
    char *str1 = "1234";
    char *str2 = "12c4";
    char *str3 = "a234";
    int num1 = atoi(str1);
    int num2 = atoi(str2);
    int num3 = atoi(str3);
    printf("変換結果:\n %s --> %d; %s --> %d; %s --> %d\n", str1, num1, str2, num2, str3, num3);
    return 0;
}

実行結果:

変換結果:
 1234 --> 1234; 12c4 --> 12; a234 --> 0

自作

以下のような作り方で、atoi関数と同じ機能を持つmy_atoi関数を作ることができる

#include <stdio.h>
#include <math.h>

int my_atoi(char *str){
  int i = 0;
  while(*(str+i)<=57&&*(str+i)>=48){
    i++;
  }
  int rsl = 0;
  if(i==0){
    return 0;
  } else {
  for(int j = 0; j < i; j++){
    rsl += (*(str+j)-48)*pow(10,(i-j-1));
  }
  return (rsl);
  }
}

自作したmy_atoiを実行して:

#include <stdio.h>
#include <math.h>

int my_atoi(char *str){
  int i = 0;
  while(*(str+i)<=57&&*(str+i)>=48){
    i++;
  }
  int rsl = 0;
  if(i==0){
    return 0;
  } else {
  for(int j = 0; j < i; j++){
    rsl += (*(str+j)-48)*pow(10,(i-j-1));
  }
  return (rsl);
  }
}
int main(void)
{
    char *str1 = "1234";
    char *str2 = "12c4";
    char *str3 = "a234";
    int num1 = my_atoi(str1);
    int num2 = my_atoi(str2);
    int num3 = my_atoi(str3);
    printf("変換結果:\n%s --> %d; %s --> %d; %s --> %d\n", str1, num1, str2, num2, str3, num3);
    return 0;
}

結果:

変換結果:
1234 --> 1234; 12c4 --> 12; a234 --> 0

うまく行った模様

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?